需要Javascript Singleton通信定义

时间:2013-09-12 09:19:09

标签: javascript jquery oop javascript-objects

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

任何一个正确的我,我在这里定义的方式单身......

我的示例代码:

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 here

1 个答案:

答案 0 :(得分: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;
}