0

所以,假设我有以下脚本:

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)并获取一个设置为 999 的新hey变量。hey.foo但是当我这样做时,hey.init(999).check()不再定义。有没有办法模仿脚本,但允许 newhey具有扩展的变量/函数?

编辑:更改hey.check()hey.init(999).check() 对此感到抱歉...

4

2 回答 2

2

您所做的实际上并不是获取一个新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);
于 2010-09-03T23:15:20.363 回答
0

这个对我有用...

当我粘贴

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();第二个日志显示了一个对象 where foo == 22.

什么对你不起作用?

于 2010-09-03T23:24:15.303 回答