Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/463.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
JavaScript:获取包含扩展变量的对象实例_Javascript_Object_Instances_Extending - Fatal编程技术网

JavaScript:获取包含扩展变量的对象实例

JavaScript:获取包含扩展变量的对象实例,javascript,object,instances,extending,Javascript,Object,Instances,Extending,假设我有以下脚本: var hey = { foo: 1, bar: 2, baz: 3, init: function(newFoo){ this.foo = newFoo; return this; } } hey.check = function(){ alert('yeah, new function'); } 基本上,我可以调用new hey.init(999)并获得一个新的hey变量,将hey.foo设

假设我有以下脚本:

var hey = {
    foo: 1,
    bar: 2,
    baz: 3,
    init: function(newFoo){
        this.foo = newFoo;
        return this;
    }
}
hey.check = function(){
    alert('yeah, new function');
}
基本上,我可以调用
new hey.init(999)
并获得一个新的
hey
变量,将
hey.foo
设置为999。但是当我这样做时,
hey.init(999).check()
不再被定义。有没有办法模仿脚本,但允许新的
拥有扩展的变量/函数

编辑:将
hey.check()
更改为
hey.init(999.check()

很抱歉…

您所做的并不是实际获得一个新的
hey
实例,而是一个
hey.init
实例,它只包含
foo
属性

我想这就是你想要做的:

var hey =function() {
    this.foo = 1;
    this.bar = 2;
    this.baz = 3;
    this.init = function(newFoo){
        this.foo = newFoo;
    }
}
hey.check = function(){
    alert('yeah, new function');
}


//now instantiating our class, and creating an object:
var heyInstance=new hey();
heyInstance.init(999);
alert(heyInstance.foo);
它对我有用

当我粘贴

var hey = {
    foo: 1,
    bar: 2,
    baz: 3,
    init: function(newFoo){
        this.foo = newFoo;
        return this;
    }
}
hey.check = function(){
    alert('yeah, new function');
}
console.log(hey);
hey.init(22);
console.log(hey);
hey.check();
在Firebug的控制台中,我收到了来自
hey.check()的警报foo==22


什么对你不起作用?

你的
是一个对象,而不是一个你可以从中实例化对象的类,我用我相信你想编码的语法编辑了我的答案。似乎起作用了。也许问题出在其他地方,或者这个问题需要重新表述。因此,如果我想在运行
init
之后返回
hey
实例,我不能只
返回这个
,因为
这个
将引用
init
。如何返回init的父
this
?实际上,您可以执行
返回此操作
将指的是
heyInstance
。但是,当您在示例代码中执行
new hey.init()
时,该
this
指的是
hey.init
实例,因为那时您实例化的是
hey.init
而不是
hey
好的,所以我只是对您的代码运行了一个快速测试,
heyInstance.check()
是未定义的。我想应该是
hey.prototype.check
而不是
hey.check
。但是
hey.prototype
跨浏览器兼容吗?比如说,IE6和FF2?是的,
嘿。prototype
是跨浏览器的,它是JavaScript的核心语法。