【问题标题】:Value of constructor and prototype gets changed after over writing the prototype object. Why?重写原型对象后,构造函数和原型的值会发生变化。为什么?
【发布时间】:2013-10-01 06:50:28
【问题描述】:

我有 Director() 函数。我从 Director() 构造函数中创建了 2 个实例 AlfredH 和 JohnD。原型对象不是我写的。

function Director(){
  this.genre = "Thriller";
}

var AlfredH = new Director();
var JohnD = new Director();   

如果我检查 JohnD.constructor 的值;和 JohnD.constructor.prototype;我分别得到 Director() 和 Object()

但是,如果我向 Director() 的原型对象添加属性,如下所示:

function Director(){
  this.genre = "Thriller";
}
Director.prototype = {
  noir: true
}; 
var AlfredH = new Director();
var JohnD = new Director();  

如果我检查 JohnD.constructor 的值;和 JohnD.constructor.prototype;我分别得到 Object() 和 Object() 。谁能解释这种行为?并且同样可以扩展到JohnD.constructor.prototype.constructor的值;

【问题讨论】:

    标签: javascript function constructor prototype instances


    【解决方案1】:
    var a = {
      value:22;
    }
    

    然后

    var a = {
      somethingelse:0
    }
    

    你能猜出a.value是什么吗?

    你正在用另一个对象覆盖原型。

    然后添加到那个

    console.log({}.constructor)===Object;//=true
    

    也许尝试像这样添加它:

    Director.prototype.noir = true;
    

    请注意,原型上的任何内容都是在实例之间共享的,这是一件好事,因为它可以节省内存并以更少的 cpu 更快地实例化对象。

    当分配一个新值时,该值被分配给实例,但是当通过函数操作该值时,它会影响所有实例

    Director.prototype.someArray=[];
    var d1=new Director();
    var d2=new Director();
    d1.someArray.push(22);
    console.log(d2.someArray);//=[22]
    

    更多关于原型的信息:https://stackoverflow.com/a/16063711/1641941

    【讨论】:

      猜你喜欢
      • 2015-03-16
      • 2010-10-07
      • 1970-01-01
      • 2014-01-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-01-17
      相关资源
      最近更新 更多