【问题标题】:Does existing constructor remain unaffected if you modify the prototype object for a constructor function?如果修改构造函数的原型对象,现有构造函数是否不受影响?
【发布时间】:2015-08-11 16:46:04
【问题描述】:

如果您修改构造函数的原型对象,则更改仅对您使用该构造函数创建的新对象可见;使用构造函数创建的现有对象将不受影响。对还是错?

【问题讨论】:

    标签: javascript prototype


    【解决方案1】:

    测试起来相当容易:

    //
    //our constructor
    function myThing(){
    
    }
    
    //create a prototype method
    myThing.prototype.foo = function(){
      return 'bar'; 
    };
    //create a prototype property
    myThing.prototype.thing = 'hello';
    
    var bar = new myThing();
    
    console.log(bar.foo());//bar
    console.log(bar.thing);//hello
    
    
    
    
    //modify prototype
    myThing.prototype.foo = function(){
      return 'baz'; 
    };
    
    myThing.prototype.thing = 'goodbye';
    
    //create new
    var bar2 = new myThing();
    
    
    
    //log old
    console.log(bar.foo()); //baz
    console.log(bar.thing); //goodbye
    
    //log new
    console.log(bar2.foo()); //baz 
    console.log(bar2.thing); //goodbye
    //
    

    如您所见,在这种情况下您的陈述是 false:如果您的对象正在使用原型方法和属性并且这些方法或属性被修改(同时保持相同的原型引用,请参阅 Oriol 的答案不同),现有对象将受到影响。

    【讨论】:

      【解决方案2】:

      没错。魔术是通过内部 [[Prototype]] 属性完成的,该属性确定对象从哪个其他对象继承。

      实例化构造函数时,实例的 [[Prototype]] 设置为当前的prototype

      稍后更改 prototype 不会影响之前的实例,它们的 [[Prototype]] 仍将指向之前的 prototype

      更改只会影响更改后创建的实例,它们的 [[Prototype]] 将设置为新的 prototype

      function F(){}
      var f1 = new F();
      f1 instanceof F; // true
      F.prototype = {foo: 'bar'}
      var f2 = new F();
      f1.foo; // undefined
      f2.foo; // "bar
      f1 instanceof F; // false
      f2 instanceof F; // true
      

      【讨论】:

        【解决方案3】:

        我不确定你的意思。现有实例不受影响是

        • true 当您将构造函数的 .prototype 属性设置为不同的原型对象时。
        • false 当您通过设置属性来修改原型对象时。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2017-11-10
          • 1970-01-01
          • 2018-04-26
          • 2022-12-18
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多