0

我制作了一个对象以保持我的函数成为单例,使用它,我制作了示例方法来相互调用和通信..但我没有得到任何适当的结果..

任何人纠正我,我在这里定义的单身方式......

我的示例代码:

var obj = window[obj] || {}; //singleton

obj.nameIt = function(name){

    this.name = name;

    this.getName = function(){
        return this.name;
    }

}

obj.sayIt = function(name){

    this.name = name; var that = this;

    this.sayHello = function(){
        console.log("say" + this.name);
        that.getName();//how to get result from nameIt?
    }

}

var x = obj.nameIt("af");
console.log(x.getName());//says "undefined" - how to call it?

var y = obj.sayIt("xy");
console.log(y.sayHello());//says "undefined" - how to call it?

jsfiddle在这里

4

1 回答 1

1

您的代码不返回任何内容。

obj.nameIt = function(name){

    this.name = name;

    this.getName = function(){
        return this.name;
    }
    return this;
}

obj.sayIt = function(name){

    this.name = name; var that = this;

    this.sayHello = function(){
        console.log("say" + this.name);
        return that.getName();
    }
    return this;
}
于 2013-09-12T09:45:06.523 回答