简述
本文是笔者看完《JavaScript面向对象编程指南》后的一些明白与感悟,仅是对JavaScript原型与多种继续举行思路上的梳理,并不是解说基础知识,合适相识原型和继续,却不够清楚透辟的开发者。
愿望列位开发者能够经由过程浏览这篇文章缕清原型和组织函数的头绪
原型(prototype)
进修原型,你须要相识
- 实例对象
- 组织函数
- 原型对象
视察以下代码
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
属性,不可控。