如何在JavaScript中定義繼承?很多新手對此不是很清楚,為了幫助大家解決這個難題,下面小編將為大家詳細講解,有這方面需求的人可以來學習下,希望你能有所收獲。
1.JavaScript主要用來向HTML頁面添加交互行為。 2.JavaScript可以直接嵌入到HTML頁面,但寫成單獨的js文件有利于結構和行為的分離。 3.JavaScript具有跨平臺特性,在絕大多數瀏覽器的支持下,可以在多種平臺下運行。
基類定義如下:
// base class
function Animal(t)
{
if(typeof t==='string')
this.type=t;
else
{
if(t)
this.type=t.toString();
else
this.type='Animal'
}
this.speak=function(str)
{
if(str)
console.log(this.type+' said '+str);
else
throw "please specify what you want to say!";
}
}1. 原型繼承 (javascript 類庫本身基于原型繼承)
String, Number , Boolean 這三大原始類型 我們可以很直接的通過prototype 檢查到他們繼承自Object.
Date, RegExp ,Array 這三應該是間接繼承了Object, 他們的prototype屬性很特殊 :
Date.prototype =Invalid Date RegExp.prototype=/(?:)/ Array.prototype=[]
原型繼承代碼如下: (可以看到Mokey 原型鏈上的Animal和Object)
// Monkey : Animal
function Monkey(name,age)
{
this.name=name;
this.age=age;
}
Monkey.prototype=new Animal('Monkey');
// Example 01
var m=new Monkey('codeMonkey',10);
/*
Monkey:
age: 10
name: "codeMonkey"
__proto__: Animal
speak: function (str)
type: "Monkey"
__proto__: Animal
constructor: function Animal(t)
__proto__: Object
*/
console.log(m.type); // Monkey
console.log(m.name); // codeMonkey
console.log(m.age); // 10
m.speak('hello world') // Monkey said hello world2. 調用父類構造函數 ( 通過傳遞子類的this指針 , 將原本是父類的公開成員直接添加到了子類中,從子類原型鏈中無法看出繼承關系)
// Human:Animal
function Human(id,name)
{
// call base class's constuctor function
Animal.call(this,'Human');
this.id=id;
this.name=name;
}
var h=new Human(1,'leon');
/*
id: 1
name: "leon"
speak: function (str)
type: "Human"
__proto__: Human
constructor: function Human(id,name)
__proto__: Object
*/
h.speak('hello world'); // Human said hello world
console.log(h.type); // Human看完上述內容是否對您有幫助呢?如果還想對相關知識有進一步的了解或閱讀更多相關文章,請關注億速云行業資訊頻道,感謝您對億速云的支持。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。