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

来源:互联网 发布:广州网络批发服装市场 编辑:程序博客网 时间:2024/05/21 20:01

創建類別

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

建立object實例

var person = new Person();

測試

typeof Person === "function";//truetypeof 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();//如未添加此行在產生實例時建構子會為父類Personchild.constructor === Person;//true  這樣感覺很奇怪,明明是new Child(); //添加後才會為正確的子類Child.prototype.constructor = Child;child.constructor === Child;
0 0
原创粉丝点击