1. 程式人生 > 其它 >js建構函式的this和prototype區別 / new 的實現

js建構函式的this和prototype區別 / new 的實現

在js建構函式裡 this 通過 new 例項生成一個獨自的一份資料;prototype 通過new 例項生成一個公用的資料;

function Vue(){
    this.name = 'vue'
}

var vm1 = new Vue();
vm1.name = 'vm1'

var vm2 = new Vue();
vm2.name = 'vm2'

下面輸出:

vm1的name 和 vm2的name 是不相同的

function Vue(){
    this.name = 'vue'
}

Vue.prototype.age = '20'

var vm1 = new Vue();
var vm2 = new Vue();
console.log(Vue.protype.age)
console.log(vm1.protype.age)
console.log(vm2.protype.age)
vm1.__proto__.age = 30  

console.log(Vue.protype.age)

console.log(vm1.protype.age)

console.log(vm2.protype.age)


vm1.__proto__.age
= 25
console.log(Vue.protype.age)
console.log(vm1.protype.age)
console.log(vm2.protype.age)

下面輸出:

vm1的age 和 vm2的age 是公用一個的

js 的new 例項做個啥呢:

  1. 建立一個空物件
  2. 將建立的空物件原型__proto__ 指向 建構函式的原型 prototype
  3. 將建構函式的this指向修改為建立的空物件
function _new(Con,...ages){
  let obj = {}
  obj.__proto__ = Con.prototype ; //Object.setPrototypeOf(obj,Con.prototype)
  Con.apply(obj,ages);
  return obj
}


function Vue(){
    this.name = 'vue'
}

let vm = _new(Vue);
console.log(vm instanceof Vue)

結果輸出: