Skip to content

new 原理和实现 #36

@chenhuiYj

Description

@chenhuiYj

步骤

1.创建一个空对象

2.把对象的__proto__属性指向父类的prototype,空对象将拥有父类的prototype的属性

3.执行构造函数,并且把this指向创建的对象,并且父类里面this的赋值(父类的属性)将赋值到新创建的对象。

4.返回对象

function Base() {
    this.id = 'base';
}

Base.prototype.toString = function() {
    return this.id;
};

var obj = new Base();

创建空对象{},obj

把obj的__proto__属性赋值到Base的prototype上面。

执行Base.call(obj,arguments),把this指向obj,把Base的属性(this的赋值)作用到obj上面

返回对象

function base(name,age) {
    this.name=name
    this.age=age
}
base.prototype.sayName=function(){
    console.log(this.name)
}
function newFn(fn,...arg){
    let obj={}
    obj.__proto__=fn.prototype
    fn.call(obj,...arg)
    return obj
}

let obj1=newFn(base,'chen',31)
let obj2=newFn(base,'lu',33)

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions