国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 語言 > JavaScript > 正文

JavaScript繼承的特性與實(shí)踐應(yīng)用深入詳解

2024-05-06 15:43:41
字體:
供稿:網(wǎng)友

本文詳細(xì)講述了JavaScript繼承的特性與實(shí)踐應(yīng)用。分享給大家供大家參考,具體如下:

繼承是代碼重用的模式。JavaScript 可以模擬基于類的模式,還支持其它更具表現(xiàn)力的模式。但保持簡單通常是最好的策略。

JavaScript 是基于原型的語言,也就是說它可以直接繼承其他對象。

1 偽類

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;});            
發(fā)表評論 共有條評論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表

圖片精選

主站蜘蛛池模板: 嘉善县| 湾仔区| 烟台市| 佳木斯市| 玛曲县| 永城市| 淮滨县| 五大连池市| 冕宁县| 龙南县| 宁化县| 元氏县| 泽库县| 万山特区| 惠州市| 东丽区| 林州市| 祁连县| 苏尼特右旗| 高台县| 花莲市| 卓资县| 曲沃县| 资兴市| 分宜县| 正定县| 蕉岭县| 华安县| 阿合奇县| 叶城县| 德格县| 嘉兴市| 深水埗区| 古丈县| 武鸣县| 揭东县| 鄂伦春自治旗| 石泉县| 丽水市| 甘谷县| 武胜县|