JavaScript之new的模拟实现

JavaScript之new的模拟实现javascript

一句话介绍bind:
new 运算符建立一个用户定义的对象类型的实例或具备构造函数的内置对象类型之一
 
new实现了哪些功能
function Otaku (name , age){
    this.name = name
    this.age = age

    this.habit = 'Games'
}

Otaku.prototype.strength = 60
Otaku.prototype.sayYourName = function(){
    console.log('I am ' + this.name)
}

var person = new Otaku('hy' , 18)

console.log(person.name)
console.log(person.age)
console.log(person.habit)
console.log(person.strength)

person.sayYourName()

由此能够看出,实例person能够:java

  1. 访问到Otaku构造函数里的属性
  2. 访问到Otaku.prototype中的属性
 
初步实现
分析:
  1. 由于new的结果是一个新对象,因此在模拟实现的时候,咱们也要创建一个新对象,假设这个新对象叫作obj
  2. 由于obj会具备Otaku构造函数里的属性,咱们能够使用Otaku.apply(obj,arguments)来给obj添加新的属性
  3. 实例的__proto__属性会指向构造函数的prototype,也正是由于创建起这样的关系,实例能够访问原型上的属性
初版
function objectFactory(){
    var obj = new Object()
    Constructor = [].shift.call(arguments)

    obj.__proto__ = Constructor.prototype

    Constructor.apply(obj , arguments)

    return obj
}

 

这一版中,咱们:
  1. 用new Object() 的方式新建了一个对象 obj
  2. 取出第一个参数,就是咱们要传入的构造函数。此外由于shift会修改原数组,因此arguments 会被去除第一个函数
  3. 将obj的原型指向构造函数,这样obj就能够访问到构造函数原型中的属性
  4. 使用apply,改变构造函数this的指向到新建的对象,这样obj就能够访问到构造函数中的属性了。
  5. 返回obj
 
返回值效果实现
function Otaku(name , age){
    this.strength = 60
    this.age = age

    return 'handsome boy';
}

var person = new Otaku('hy', '18');

console.log(person.name) // undefined
console.log(person.habit) // undefined
console.log(person.strength) // 60
console.log(person.age) // 18

第二版数组

function objectFactory(){
    var obj = {}
    Constructor = [].shift.call(arguments)
    obj.__proto__ = Constructor.prototype
    var ret = Constructor.apply(obj , arguments)
    return typeof ret === 'object' ? ret : obj
}
相关文章
相关标签/搜索