React原型链解析

前言

使用原型链的作用:

当我们需要创建很多对象且这个对象都有一个相同的方法
在这里插入图片描述
我们可能会需要写很多遍这个方法。但是有了原型链,我们可以将这个方法写在函数的prototype里,这样每个新创建的对象都能直接拿到这方法。

原型链

首先,我们要知道
每个方法 都有一个prototype
每个对象都有一个__proto__和constructor
方法也是对象,所以方法也有__proto__和constructor ,即方法有__proto__和constructor和prototype

假设存在方法foo和对象o

function foo(name, age) {
    this.name = name
    this.age = age
    this.showName = function () {
        console.log("my name is:", name);
    }
}
var o = new foo()

*****
因为o是由foo创建,所以foo是o的构造函数,即
o.constructorfoo()

console.log(o.constructor);

在这里插入图片描述
*****
o的__proto__指向foo的prototype,即
o.__proto__foo.prototype

console.log(o.__proto__==foo.prototype);//true

*****
又因为prototype是一个对象

console.log(foo.prototype);

在这里插入图片描述

所以foo.prototype.proto ⇒ Object.prototype

console.log(foo.prototype.__proto__==Object.prototype); //true

*****
对象的构造函数都是指向创建他的方法

console.log(o.constructor);

在这里插入图片描述
*****
object再往上找不到别的函数了,所以
Object.prototype.__proto__==null

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值