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
}
相關文章
相關標籤/搜索