老生常談--Js繼承小結

      一直以來,對Js的繼承有所認識,可是認識不全面,沒什麼深入印象。因而,常常性的浪費不少時間從新看博文學習繼承,今天工做不是特別忙,有幸看到了http://www.slideshare.net/stoyan/javascript-patterns?from_search=9 (該博文做者一樣是《Javascript Patterns》一書的做者,效力於Yahoo,是YSlow 的架構者和smush.it的做者),在此,本身作一些小結和筆錄以避免屢次重複學習。javascript

js繼承:java

/*******繼承1:複製父親對象全部屬性-->子對象**********/
function extend(parent, child){
var child = child || {};
for(var prop in parent){
child[prop] = parent[prop];
}
return child;
}架構

/*******混合繼承:從多個對象中繼承****************/
function mixInThese(){
var args = arguments,
child = {};
for(var i = 0, len = args.length; i < len; i++){
for(var prop in args[i]){
child[prop] = args[i][prop];
}
}
return child;
}
var cake = mixInThese(app

       {"oil": 3, "button": 4},ide

       {"weight": 34},函數

      {"tasty": "sweet"});
console.log(cake);學習

/*************經典繼承 原型繼承 ES標準推薦 繼承方式1***************************/
function inherit(parent, child){
child.prototype = new Parent();
}this

/**********借用構造函數    繼承方式2********/
function Child(){
Parent.apply(this, arguments);
//anything else
}.net

優勢:建立對象的時候,能夠傳遞參數到父親對象prototype

缺點:沒有繼承Prototype原型鏈上的屬性

/*****************/

/***********借用構造函數 + 原型繼承 繼承方式3*****************/
function Child(){
Parent.apply(this, arguments);
}
Child.prototype = new Parent();

 

/**************父子對象共用同一份prototype*  繼承方式4*********************************/
function inherit(parent, child){
child.prototype = child.prototype;
};

優勢:父子對象共用同一份prototype

缺點:父子對象共用同一份prototype

/***********只繼承prototype上的屬性(父子對象不共用同一份prototype) 繼承方式5************/
function inherit(parent, child){
function F(){}
F.prototype = parent.prototype;
child.prototype = new F();

child.uber = parent.prototype;

child.prototype.constructor = child;
}

/**********原生式繼承Prototypal inhert************/

function object(o){

    function F(){}

   F.prototype = o;

   return new F();

}

 

原生式繼承總結(道格拉斯總結):

1.沒有像類(Class-Like)同樣的構造函數(Constructor)(英文原文:no class-like constructors).

2.對象和對象之間直接經過原型實現繼承(而不像其餘語言中的類和類之間的繼承)(英文原文:objects inherits from objects)。

相關文章
相關標籤/搜索