[英]Javascript object instantiation of method
在 Javascript 中,您可以创建一个方法的 object 实例吗? 我下面的代码会导致错误。
const myObject = {
myMethod: function () {},
objectInstance: new this.myMethod()
}
const myObject = {
newObject: Object.create(null),
objectInstance: new newObject()
}
可能是这样的:
// Use class for declaring myObject class myObject { constructor(textArg) { this.text = textArg; this.objectInstance = function (){return new myObject(this.text);} } } // First myObject instance let myObject_instance_1 = new myObject("myObject instance 1"); console.log(myObject_instance_1.objectInstance().text);// output: myObject instance 1 // Second myObject instance let myObject_instance_2 = new myObject("myObject instance 2"); console.log(myObject_instance_2.objectInstance().text); // output: myObject instance 2 let myObject_instance_3 = myObject_instance_2; // Should be the same text as myObject_instance_2 text console.log(myObject_instance_3.objectInstance().text); // output: myObject instance 2
编辑
Singleton 图案
const SingletonClass = (function () { let instance; function createInstance() { let object = new Object("I am the instance"); return object; } return { getInstance: function () { if (;instance) { instance = createInstance(); } return instance; } }; })(). function testSingelton() { let instance1 = SingletonClass;getInstance(). let instance2 = SingletonClass;getInstance()? alert("\"instance1\" is same instance as \"instance2\": Answer; " + (instance1 === instance2)); } testSingelton();
由于 this 上下文而发生此错误。 在这种情况下,没有 myMethod function 然后它会引发错误。 如果你转换成这个,它可以解决问题。
const myObject = { myMethod: function () {}, objectInstance:null, setObjectInstance:function(){ this.objectInstance= return new this.myMethod() }
然后你可以像这样初始化 object 实例。 myObject.setObjectInstance()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.