本文是笔者看完《JavaScript面向对象编程指南》后的一些理解与感悟,仅是对JavaScript原型与多种继承进行思路上的梳理,并不是讲解基础知识,适合了解原型和继承,却不够清晰透彻的开发者。
但愿各位开发者可以经过阅读这篇文章缕清原型和构造函数的脉络javascript
观察如下代码java
function Person (){ this.age = 20; } Person.prototype.gender = 'male'; var tom = new Person(); tom.name = 'tom'; console.log(tom.name); // tom console.log(tom.age); // 20 console.lot(tom.gender); // male tom.constructor === Person; // true tom.__proto__ === Person.prototype; // true
function Dog(){ this.tail = true; } var benji = new Dog(); var rusty = new Dog(); // 给原型添加方法 Dog.prototype.say = function(){ return 'woof!'; } benji.say(); // "woof!" rusty.say(); // "woof!" benji.constructor === Dog; // true rusty.constructor === Dog; // true // 此时,一切正常 Dog.prototype = { paws: 4, hair: true }; // 彻底覆盖 typeof benji.paws; // "undefined" benji.say(); // "woof!" typeof benji.__proto__.say; // "function" typeof benji.__proto__.paws; // "undefined" // 原型对象不能访问原型的"新增属性",但依然经过神秘的链接 __proto__ 与原有原型对象保持联系 // 新增实例 var lucy = new Dog(); lucy.say(); // TypeError: lucy.say is not a function lucy.paws; // 4 // 此时 __proto__ 指向了新的原型对象 // 因为constructor是存储在原型对象中的,因此新实例的constructor属性就不能再保持正确了,此时它指向了Object() lucy.constructor; // function Object(){[native code]} // 旧实例的constructor仍是正确的 benji.constructor; /* function Dog(){ this.tail = true; }*/ // 若想让constructor正确,必须在新的原型对象中设置constructor属性为Dog Dog.prototype.constructor = Dog;
constructor
属性在Person.prototype
对象中,即原型对象中。__proto__
属性是在 tom(实例)
被 new
的一瞬间创建的,指向原型对象即 Person.prototype
tom.constructor
等同于 tom.__proto__.constructor
访问到的__proto__
属性只能在学习或调试的环境下使用var tom = new Person()
执行时,首先开辟一个新的地址空间用来建立并存放tom对象
,再使Person
的this
指向tom对象而且执行Person
函数。constructor
属性,不可控。