var object = new Object() 時(shí),發(fā)生了什么?
- 創(chuàng)建一個(gè)空對(duì)象作為
this
-
this.__proto__
指向構(gòu)造函數(shù)的prototype
- 運(yùn)行構(gòu)造函數(shù)
- 返回
this
以上步驟通過(guò)關(guān)鍵字 new 全部搞定
如何手動(dòng)指定對(duì)象的原型鏈
有 3 種方法
object.__proto__ = {...}
優(yōu)點(diǎn):簡(jiǎn)單直接;
缺點(diǎn):這是ES6的方法,IE8以下不支持;借用 new
var myProto = {
name: 'foo'
}
var obj = {}
var Temp = function(){}
Temp.prototype = myProto
obj = new Temp()
-
使用 Object.create(proto)
以proto對(duì)象為原型,創(chuàng)建一個(gè)新的對(duì)象
JS實(shí)現(xiàn)類(lèi)的繼承
var Animal = function(){
this.種類(lèi) = "動(dòng)物"
}
Animal.prototype.say = function(){
console.log(this.種類(lèi) + "叫");
}
var Cat = function(){
Animal.apply(this, arguments)
this.tail = "貓尾巴"
}
//下面三行代碼只為了實(shí)現(xiàn) Cat.prototype.__proto__ = Animal.prototype
//為了兼容IE67
var F = function(){};
F.prototype = Animal.prototype;
Cat.prototype = new F();
//糾正一下 constructor
Cat.prototype.constructor = Cat;
//給 Cat 賦自己的屬性
Cat.prototype.run = function(){
console.log("貓兒在跑");
}
Cat.prototype.say = function(){
console.log("喵喵喵");
}
var cat = new Cat()
console.dir(cat)
Paste_Image.png
不用類(lèi)也能實(shí)現(xiàn)繼承
var animal = {
"種類(lèi)": "動(dòng)物",
say: function(){
console.log("動(dòng)物叫");
}
}
var cat = Object.create(animal) // 創(chuàng)建以 animal 為原型的空對(duì)象
cat.tail = "貓尾巴"
cat.say = function(){
console.log("喵喵喵");
}
console.dir(cat)
Paste_Image.png