需要 Javascript Singleton 通信定义

Javascript Singleton communication definition required

本文关键字:定义 通信 Singleton Javascript 需要      更新时间:2023-09-26

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

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

我的示例代码:

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 在这里

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

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;
}