关于JS继承的一道题

关于JS继承的一道题

偶尔看到一篇字节的面试题,大概意思就是下面:

// A code block
function Animal(name){
	this.name = name||'Animal';
}

const Cat = Animal.mybind(null,'cat');
const cat = new Cat();
console.log(cat.name);//cat;
console.log(cat instanceof Cat);//true
console.log(cat instanceof Animal);//true;

这道题主要还是考察对原型和继承的理解,从题目可以看出目标就是通过方法mybind实现一个继承的子类关系。下面分别从Es5和Es6探讨一下。

//es5
Function.prototype.mybind=function(obj,name){
    const fn = this;//这个this的指向是引用这个方法的对象,就是下文中Animal;
    function newFn(...args){
        fn.call(this,...args);//这里的this则是通过new的时候的实例
        this.name = name
    }
    newFn.prototype = new fn();
    return newFn;
}
function Animal(name){
	this.name =  name||'Animal';
}
const Cat = Animal.mybind(null,'cat');
const cat = new Cat();
console.log(cat.name);//cat;
console.log(cat instanceof Cat);//true
console.log(cat instanceof Animal);//true;

从上边的代码我们可以看出用到了构造继承和原型继承两个,构造继承的实例把原型实例屏蔽了。

Function.prototype.mybind=function(obj,name){
    // const fn = this;
    class newC extends this{
        constructor(value){
            super(value);
            this.name = name ||value;
        }
    }
    return newC;
}
class Animal{
    constructor(name){
        this.name = name || 'Animal';
    }
}

const Cat = Animal.mybind(null,'cat');

const cat  =  new Cat();

console.log(cat instanceof Cat);
console.log(cat instanceof Animal);
console.log(cat.name);

E6的写法相对简单了许多,不用考虑使用构造函数继承,还是原型继承等等。直接调用类的继承extends就可以了。

还有Object.crate去实现,使用现有的对象来提供新创建的对象的__proto__,如果不清楚__proto__可以去专门了解一下,js在运行上下文的时候,寻找一个属性的时候会沿着作用域链往上一直往上寻找,知道null为止。即子类的__proto__属性总是指向父类。

Function.prototype.mybind=function(obj,name){
    // const fn = this;
    function newFn(...args){
    }
    newFn.prototype = Object.create(this.prototype);
    newFn.prototype.name = name;
    return  newFn;
}
function Animal(name){
    this.name = name || "Animal";
}

const Cat = Animal.mybind(null,'cat');

const cat  =  new Cat();

console.log(cat instanceof Cat);
console.log(cat instanceof Animal);
console.log(cat.name);
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值