JavaScript 原型与原型链

__proto__ 用来获取和设置对象原型,但它是非标准的。__proto__前后的双下划线,说明它本质上是一个内部属性,而不是一个正式的对外的API,只是由于浏览器广泛支持,才被加入了ES6。标准明确规定,只有浏览器必须部署这个属性,其他运行环境不一定需要部署,而且新的代码最好认为这个属性是不存在的。因此,无论从语义的角度,还是从兼容性的角度,都不要使用这个属性,而是使用下面的Object.setPrototypeOf()(写操作)、Object.getPrototypeOf()(读操作)、Object.create()(生成操作)代替。

创建对象的各种方式 对其原型链的影响

var o = {a: 1};
Object.getPrototypeOf(o) === Object.prototype  //true

// o ---> Object.prototype ---> null

var a = ["yo", "whadup", "?"];
// a ---> Array.prototype ---> Object.prototype ---> null

function f(){
  return 2;
}
// f ---> Function.prototype ---> Object.prototype ---> null

普通对象 o 的原型 指向 Object对象的prototype属性。

数组对象 a 的原型 指向 Array对象的prototype属性。 而 Array对象的 prototype属性也是对象,它的原型 指向 Object.prototype属性。

函数f 的原型 指向 Function对象的prototype属性。 

 

function Graph() {
  this.vertices = [];
  this.edges = [];
}

Graph.prototype = {
  addVertex: function(v){
    this.vertices.push(v);
  }
};

var g = new Graph();

var r = Object.getPrototypeOf(g) === Graph.prototype ; // true
var s =Object.getPrototypeOf(g) === Graph ; // false

使用new 关键字来创建对象。对象g 的原型指向 Graph.prototype。 (注意区别g的原型指向 Graph )

var a = {a: 1}; 
// a ---> Object.prototype ---> null

var b = Object.create(a);
// b ---> a ---> Object.prototype ---> null
var r = Object.getPrototypeOf(b) === a.prototype ;
var s =Object.getPrototypeOf(b) === a ;console.log(b.a); // 1 (inherited)

var c = Object.create(b);
// c ---> b ---> a ---> Object.prototype ---> null

var d = Object.create(null);
// d ---> null
console.log(d.hasOwnProperty); 

使用Object.create来创建对象,b的原型指向了a ,(注意不是a.prototype)

class Polygon {
  constructor(height, width) {
    this.height = height;
    this.width = width;
  }
}

class Square extends Polygon {
  constructor(sideLength) {
    super(sideLength, sideLength);
  }
  get area() {
    return this.height * this.width;
  }
  set sideLength(newLength) {
    this.height = newLength;
    this.width = newLength;
  }
}

var sq = new Square(2);

使用class 创建对象sq 的原型指向Square.prototype ,  而 子类Square 的原型 指向父类 Polygon (注意不是Polygon.prototype)

 

参考链接:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Inheritance_and_the_prototype_chain

posted @ 2016-12-07 17:29  没离开过  阅读(202)  评论(0编辑  收藏  举报