博客
关于我
回想继承、原型与原型链有感
阅读量:449 次
发布时间:2019-03-06

本文共 1639 字,大约阅读时间需要 5 分钟。

首先需要明确以下几点:

1. js中除了Object.prototype和null之外,每一个对象都有一个原型对象。

2. 获取原型对象: 实例对象通过__proto__,构造函数通过prototype。

3. Object.defineProperty()和Object.assign()之类的函数(不在原型链上的函数)是不能通过继承获得的。

4. arguments.callee需要在函数声明的时候调用,arguments.caller需要在函数执行的时候调用。

5. 每个对象的构造函数都在其原型对象上。

 

除了ES6中的继承之外,我们常用的有以下三种:

*注意:网上有很多分享都说用call继承属性,用原型链拷贝继承方法。这种观点是错误的。用call同样可以继承方法,但,此方法必须是当前实例对象上的方法,而不是原型链上的方法。用原型链也一样可以继承属性,但,此属性必须是原型链上的,而非实例对象本身的。

1.俗称类式继承

通过call或apply实现实例对象的属性或方法(this.XXXXX)的继承

通过 B.prototype = new A() 实现原型链上的属性或方法的继承
通过 B.prototype.constructor = A 实现constructor的指向更正

function People (name, age) {    this.name = name;    this.age = age;    this.eat = function () {        console.log(this.name + ": people eat !");    };}People.prototype.protoEat = function () {    console.log(this.name + "proto eat !!");}function Student (name, age) {    People.call(this, name, age);    Student.prototype.constructor = Student;}Student.prototype = new People();

2.俗称拷贝继承

通过call或apply实现实例对象的属性或方法(this.XXXXX)的继承

通过 循环 B.prototype[i] = A.prototype[i] 实现对原型链上的属性或方法的继承

function People (name, age) {    this.name = name;    this.age = age;    this.eat = function () {        console.log(this.name + ": eat !")    }}People.prototype.protoEat = function () {    console.log(this.name + "proto eat !!");}function Student (name, age) {    People.call(this, name, age);}for(var i in People.prototype){    Student.prototype[i] = People.prototype[i]}

3.普通对象做顶层进行向下继承

相当于是只通过原型继承了原型链上的属性和方法

var obj = {name: "People", eat: function () {console.log("eat fn !")}};function clone (obj) {    var Fn = function () {};    Fn.prototype = obj;    return new Fn();}var tt = clone(obj)tt.eat();

 

转载地址:http://isufz.baihongyu.com/

你可能感兴趣的文章
mysql 敲错命令 想取消怎么办?
查看>>
Mysql 整形列的字节与存储范围
查看>>
mysql 断电数据损坏,无法启动
查看>>
MySQL 日期时间类型的选择
查看>>
Mysql 时间操作(当天,昨天,7天,30天,半年,全年,季度)
查看>>
MySQL 是如何加锁的?
查看>>
MySQL 是怎样运行的 - InnoDB数据页结构
查看>>
mysql 更新子表_mysql 在update中实现子查询的方式
查看>>
MySQL 有什么优点?
查看>>
mysql 权限整理记录
查看>>
mysql 权限登录问题:ERROR 1045 (28000): Access denied for user ‘root‘@‘localhost‘ (using password: YES)
查看>>
MYSQL 查看最大连接数和修改最大连接数
查看>>
MySQL 查看有哪些表
查看>>
mysql 查看锁_阿里/美团/字节面试官必问的Mysql锁机制,你真的明白吗
查看>>
MySql 查询以逗号分隔的字符串的方法(正则)
查看>>
MySQL 查询优化:提速查询效率的13大秘籍(避免使用SELECT 、分页查询的优化、合理使用连接、子查询的优化)(上)
查看>>
mysql 查询,正数降序排序,负数升序排序
查看>>
MySQL 树形结构 根据指定节点 获取其下属的所有子节点(包含路径上的枝干节点和叶子节点)...
查看>>
mysql 死锁 Deadlock found when trying to get lock; try restarting transaction
查看>>
mysql 死锁(先delete 后insert)日志分析
查看>>