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的核心语法。