JavaScript原型与构造函数笔记

简述

本文是笔者看完《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对象,再使Personthis指向tom对象并且执行Person函数。
  • 不要过分依赖constructor属性,不可控。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值