面向?qū)ο?/h1>

var object = new Object() 時(shí),發(fā)生了什么?

  1. 創(chuàng)建一個(gè)空對(duì)象作為 this
  1. this.__proto__指向構(gòu)造函數(shù)的prototype
  2. 運(yùn)行構(gòu)造函數(shù)
  3. 返回 this

以上步驟通過(guò)關(guān)鍵字 new 全部搞定

如何手動(dòng)指定對(duì)象的原型鏈

有 3 種方法

  1. object.__proto__ = {...}
    優(yōu)點(diǎn):簡(jiǎn)單直接;
    缺點(diǎn):這是ES6的方法,IE8以下不支持;

  2. 借用 new

var myProto = {
    name: 'foo'
}
var obj = {}
var Temp = function(){}
Temp.prototype = myProto
obj = new Temp()
  1. 使用 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
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

推薦閱讀更多精彩內(nèi)容