实例之间共享哪些原型属性

时间:2014-03-11 15:23:42

标签: javascript

http://jsfiddle.net/F5ZSA/1/

这里是上面的代码:

"use strict";

function Human()
{
    this.myname;
    this.things = [];
    this.addThing = function(string)
    {
        this.things.push(string);
    }

    this.getThings = function()
    {
        return this.things;
    }

    this.setName = function(name)
    {
        this.myname = name;   
    }

    this.getName = function()
    {
        return this.myname;   
    }
}

Mister.prototype = new Human();
function Mister()
{

}

var mister1 = new Mister();
var mister2 = new Mister();

mister1.setName("Peter");
mister2.setName("Steven");

mister1.addThing("mister1 reporting");
mister2.addThing("mister 2 reporting");

console.log(mister1.getName());
console.log(mister2.getName());
console.log(mister1.getThings());
console.log(mister2.getThings());

当你运行它时,结果表明' myname'每个Mister实例的属性都不同,而“事物”则不同。属性似乎在所有实例之间共享。是假设是那样的吗?如果是,那么通用规则告诉我们在继承'之间共享哪些原型属性。对象

来自其他OOP语言,我的直觉是每个对象都应该有一个单独的原型实例。尝试在js中强制执行它是个好主意吗?

1 个答案:

答案 0 :(得分:2)

这是来自传统OOP语言的经典问题。通过创建新对象,可以复制原型。关键字' this'已经引用了新对象,但是从原型中引用另一个对象作为你的this.things仍然指向内存中的相同空间。创建两个对象时,您将创建对同一对象的两个引用(在本例中为数组)

以下内容将按您的预期运行。绕过这个'问题我在那里调用初始化对象的init方法,在这种情况下创建多个数组对象,每个对象用于新对象Mister。

var Human = function()
{

    this.myname;
    this.things;
    this.things;

    return {
      addThing:function(string)
      {
          this.things.push(string);
      },

      getThings:function()
      {
          return this.things;
      },

      setName: function(name)
      {
          this.myname = name;
      },

      getName: function()
      {
          return this.myname;
      },
      init: function(){
              this.things = new Array();
            }
    }

}


var Mister = function(){}
Mister.prototype = new Human();

var mister1 = new Mister();
var mister2 = Object.create(Mister.prototype);
mister1.init();
mister2.init();


mister1.setName("Peter");
mister2.setName("Steven");

mister1.addThing("mister1 reporting");
mister2.addThing("mister 2 reporting");

console.log(mister1.getName());
console.log(mister2.getName());
console.log(mister1.getThings());
console.log(mister2.getThings());