【问题标题】:Javascript object instantiation of method方法的Javascript对象实例化
【发布时间】:2020-12-04 21:47:20
【问题描述】:

在 Javascript 中,您可以创建方法的对象实例吗?我下面的代码会导致错误。

const myObject = {
    myMethod: function () {},
    objectInstance: new this.myMethod()
}
const myObject = {
    newObject: Object.create(null),
    objectInstance: new newObject()
}

【问题讨论】:

    标签: javascript object methods instantiation


    【解决方案1】:

    可能是这样的:

       // 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

    编辑

    单例模式

    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();

    【讨论】:

      【解决方案2】:

      由于 this 上下文而发生此错误。在这种情况下,没有 myMethod 函数,然后它会引发错误。如果你转换成这个它可以解决问题。

      const myObject = { 我的方法:函数(){}, 对象实例:空, 设置对象实例:函数(){ this.objectInstance= 返回新的 this.myMethod() }

      } 然后你可以像这样初始化对象实例。 myObject.setObjectInstance()

      【讨论】:

        猜你喜欢
        • 2015-09-23
        • 1970-01-01
        • 2015-11-01
        • 1970-01-01
        • 1970-01-01
        • 2012-03-19
        • 2010-09-29
        • 1970-01-01
        • 2023-03-15
        相关资源
        最近更新 更多