javascript物件導向(1)--創建類別和繼承示範

創建類別

function Person(){}
var Person = function(){};

建立object實例

var person = new Person();

 

測試

typeof Person === "function";//true
typeof person === "object";    //true

每當我們產生一個新物件時,同時會產生一個構造式constructor,這個constructor會等於我們建立物件時宣告的function

person.constructor === Person; //true

簡單繼承示範

var Person = function(){};
var Child = function(){};
//孩子繼承雙親
Child.prototype = new Person();
Child.prototype.constructor = Child;

其中請注意需添加Child.prototype.constructor = Child;

var Person = function(){};
var Child = function(){};
Child.prototype = new Person();

var Person = function(){};
var Child = function(){};
Child.prototype = new Person();
//產生實例
var child = new Child();

//如未添加此行在產生實例時建構子會為父類Person
child.constructor === Person;//true  這樣感覺很奇怪,明明是new Child(); 
//添加後才會為正確的子類
Child.prototype.constructor = Child;
child.constructor === Child;

 

 

 

 

 


因為很多文章是過往自己搜集的資料、圖片,如有侵權疑慮請告知,將立即下架刪除。