如何理解javascript的原型链

对于原型链的理解:

1.js实现封装继承的方法。

2.关键点:构造函数生成的实例对象的__proto__指向构造函数的protorype属性。利用这个特点,js实现了构造函数的数据与方法共享给实例对象。

Instanceof 的原理也是原型链。

ES6的 class只是语法糖,本质还是原型链的实现方式。

 

原型链的图:

js实现 面向对象编程方式的demo:

function Parent() {
    this.name = 'ssx'
}

var Child = function (age) {
    Parent.call(this)
    this.age = age
}
Child.prototype = Object.create(Parent.prototype)
Child.prototype.constructor = Child
Child.prototype.setAge = function(age){
    this.age = age
}

var s = new Child(18)
console.log("名字",s.name)
console.log("年龄",s.age)
s.setAge(20)
console.log("年龄",s.age)

理解原型链还要理解new 关键字做了什么,demo:

function testF(name){
    this.name = name
}
var testObj = new testF('ssx')
console.log("testObj------",testObj)

function newF(fun,arg) {
    let o = Object.create(fun.prototype)
    let temp = fun.call(o,arg)
    if(typeof temp === 'Object'){
        return temp
    }else {
        return o
    }
}

var testObj2 = newF(testF,'ssx')
console.log("testObj2------",testObj2)

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值