本文詳細(xì)講述了JavaScript繼承的特性與實(shí)踐應(yīng)用。分享給大家供大家參考,具體如下:
繼承是代碼重用的模式。JavaScript 可以模擬基于類的模式,還支持其它更具表現(xiàn)力的模式。但保持簡單通常是最好的策略。
JavaScript 是基于原型的語言,也就是說它可以直接繼承其他對象。
JavaScript 的原型不是直接讓對象從其他對象繼承,而是插入一個(gè)多余的間接層:通過構(gòu)造函數(shù)來產(chǎn)生對象。
當(dāng)一個(gè)函數(shù)被創(chuàng)建時(shí),F(xiàn)unction 構(gòu)造器產(chǎn)生的函數(shù)對象會(huì)運(yùn)行這樣類似的代碼:
this.prototype = {constructor : this};新的函數(shù)對象新增了一個(gè) prototype 屬性,它是一個(gè)包含了 constructor 屬性且屬性值為該新函數(shù)的對象。
當(dāng)采用構(gòu)造器調(diào)用模式,即用 new 去調(diào)用一個(gè)函數(shù)時(shí),它會(huì)這樣執(zhí)行:
Function.method('new', function (){ var that = Object.create(this.prototype);//創(chuàng)建一個(gè)繼承了構(gòu)造器函數(shù)的原型對象的新對象 var other = this.apply(that, arguments);//調(diào)用構(gòu)造器函數(shù),綁定 this 到新對象 return (typeof other === 'object' && other) || that;//如果構(gòu)造器函數(shù)的返回值不是對象,就直接返回這個(gè)新對象});我們可以定義一個(gè)構(gòu)造器,然后擴(kuò)充它的原型:
//定義構(gòu)造器并擴(kuò)充原型var Mammal = function (name) { this.name = name;};Mammal.prototype.get_name = function () { return this.name;};Mammal.prototype.says = function () { return this.saying || '';};然后構(gòu)造實(shí)例:
var myMammal = new Mammal('Herb the mammal');console.log(myMammal.get_name());//Herb the mammal構(gòu)造另一個(gè)偽類來繼承 Mammal(定義構(gòu)造器函數(shù)并替換它的 prototype):
var Cat = function (name) { this.name = name; this.saying = 'meow';};Cat.prototype = new Mammal();擴(kuò)充原型:
Cat.prototype.purr = function (n) { var i, s = ''; for (i = 0; i < n; i += 1) { if (s) { s += '-'; } s += 'r'; } return s;};Cat.prototype.get_name = function () { return this.says() + ' ' + this.name + ' ' + this.says();};var myCat = new Cat('Henrietta');console.log(myCat.says());//meowconsole.log(myCat.purr(5));//r-r-r-r-rconsole.log(myCat.get_name());//meow Henrietta meow我們使用 method 方法定義了 inherits 方法,來隱藏上面這些丑陋的細(xì)節(jié):
/** * 為 Function.prototype 新增 method 方法 * @param name 方法名稱 * @param func 函數(shù) * @returns {Function} */Function.prototype.method = function (name, func) { if (!this.prototype[name])//沒有該方法時(shí),才添加 this.prototype[name] = func; return this;};Function.method('inherits', function (Parent) { this.prototype = new Parent(); return this;});
新聞熱點(diǎn)
疑難解答
圖片精選