new关键字生成实例做了啥

20200105.jpg

风停在窗边,嘱咐我要热爱这个世界

function Human (name, age) {
    this.name = name
    this.age = age

    this.say = function () {
        console.log(`my name is ${this.name}, my age is ${this.age}`);
    }
}

Human.prototype.color = 'yellow'
Human.prototype.sayHello = function () {
    console.log('Hello!');
}

let human = new Human('kobe', 25)

console.log(human);

human.sayHello()

console.log('--------------------------');

console.log(human.color);



截图如下


image.png

根据上面我们来看一下new都干了啥

  • 初始化新对象
let obj = {}
  • 原型的执行,确定实例对象的构造函数
obj._proto_ = Human.prototype
  • 绑定this指向对象为obj,传入参数,执行Human构造函数,进行属性和方法的赋值操作
Human.call(obj, 'kobe', 25)

如果我们不使用new关键字的话,而是直接调用Human () ,那么此时this指向就是window,而使用了new的话,指向的就是Human本身了

  • 返回该对象
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容