理解Javascript的Prototype

在Javascript中创建对象主要分为三种方式

1、

var catA = {name: "Fluffy", color: "White", age: 0};

2、

var catB = Object.create(new Object());
catB.name = "Fluffy";
catB.color = "White";
catB.age = 0;

3、

function Cat(name, color) {
  this.name = name;
  this.color = color;
}
Cat.prototype.age = 0;

var catC = new Cat("Fluffy", "White");

 每个函数都有个prototype属性,这是一个对象。如果访问一个对象的属性,首先会在对象内部查找,如果再对象内部中找不到这个属性,会到原型中去找,以此类推。通过每个对象会有一个__proto__来指向prototype。如果对象不是new出来的,则__proto__为{}如

catA.__proto__;
Object { }

  

catC.__proto__;
Cat {age: 0}

  通过调用对象的hasOwnProperty可以判断非原型上定义的属性比如

catC.hasOwnProperty("name");
true

catC.hasOwnProperty("color");
true

catC.hasOwnProperty("age");
false

改变函数原型对象的属性,会引起对象属性的变化比如。因为有函数new出来的对象中的__proto__指向的是同一个对象即函数的prototype属性。

function Cat(name, color) {
  this.name = name;
  this.color = color;
}
Cat.prototype.age = 3;

var fluffy = new Cat("Fluffy", "White");
var scratchy = new Cat("Scratchy", "Black");

fluffy.age;
3

scratchy.age;
3

Cat.prototype.age = 4;

fluffy.age;
4

scratchy.age;
4

如果对象已经早已被new出来了,后来又改变了构造该对象函数的原型。则不会影响到原来对象的属性变化,因为__proto__还是指向原来的那个对象。 

function Cat(name, color) {
  this.name = name;
  this.color = color;
}
Cat.prototype.age = 3;

var fluffy = new Cat("Fluffy", "White");
var scratchy = new Cat("Scratchy", "Black");

fluffy.age;
3

scratchy.age;
3

Cat.prototype = {age: 4};

fluffy.age;
3

scratchy.age;
3

var muffin = new Cat("Muffin", "Brown");

muffin.age;
4

因为每个对象都有个__proto__属性来指向原型对象,因此如果改变通过该对象的__proto__可以改变原型的属性,从而影响其他已经或者即将new的对象。

function Cat(name, color) {
  this.name = name;
  this.color = color;
}
Cat.prototype.age = 3;

var fluffy = new Cat("Fluffy", "White");
var scratchy = new Cat("Scratchy", "Black");
Compare this example:

fluffy.age = 4;

fluffy.age;
4

scratchy.age;
3
To this example:

fluffy.__proto__.age = 4;

fluffy.age;
4

scratchy.age;
4

javascript 继承的实现

function Animal(name) {
  this.name = name;
}
Animal.prototype.age=1;

function Cat(name, color) {
  Animal.call(this, name);
  this.color = color;
}
Cat.prototype = new Animal(null);

var catC = new Cat("Fluffy", "White");

catC.name;
Fluffy

catC.color;
White

catC.age;
1
原文地址:https://www.cnblogs.com/dubaokun/p/3431025.html