js篇-new实现

对于大部分前端开发者而言,new一个构造函数或类得到对应实例,是非常普遍的操作了。下面的例子中通过构造函数与与class类实现了一个简单的创建实例的过程

// ES5构造函数
let Parent = function (name, age) {
        this.name = name;
        this.age = age;
};
Parent.prototype.sayName = function () {
        console.log(this.name);
};
const child = new Parent('听风是风', 26);
child.sayName() //'听风是风'


//ES6 class类
class Parent {
        constructor(name, age) {
                this.name = name;
                this.age = age;
        }
        sayName() {
                console.log(this.name);
        }
};
const child = new Parent('echo', 26);
child.sayName() //echo

第一,js中new一个对象时到底发生了什么第二,知道了原理后我们通过js来实现一个简单的new方法

在《JavaScript模式》这本书中,new的过程说的比较直白,当我们new一个构造器,主要有三步:

1.创建一个空对象, 将它的引用赋给 this, 继承函数的原型

2.通过 this 将属性和方法添加至这个对象

3.最后返回 this 指向的新对象, 也就是实例 (如果没有手动返回其他的对象)

-----------------------------------------------------------------------------------------------------------

我们改写上面的例子,大概就是这样:

// ES5构造函数
let Parent = function (name, age) {
        //1.创建一个新对象,赋予this,这一步是隐性的,
        // let this = {};
        //2.给this指向的对象赋予构造属性
        this.name = name;
        this.age = age;
        //3.如果没有手动返回对象,则默认返回this指向的这个对象,也是隐性的
        // return this;
};
const child = new Parent();

实现一个简单的new方法

// 构造器函数
let Parent = function (name, age) {
        this.name = name;
        this.age = age;
};
Parent.prototype.sayName = function () {
        console.log(this.name);
};
//自己定义的new方法
let Child = function (Parent, ...rest) {
        // 1.以构造器的prototype属性为原型,创建新对象;
        let child = Object.create(Parent.prototype);
        // 2.将this和调用参数传给构造器执行
        let result = Parent.apply(child, rest);
        // 3.如果构造器没有手动返回对象,则返回第一步的对象
        return typeof result  === 'object' ? result : child;
};
//创建实例,将构造函数Parent与形参作为参数传入
const child = Child (Parent, 'echo', 26);
child.sayName() //'echo';

//最后检验,与使用new的效果相同
child instanceof Parent//true
child.hasOwnProperty('name')//true
child.hasOwnProperty('age')//true
child.hasOwnProperty('sayName')//false

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值