码迷,mamicode.com
首页 > Web开发 > 详细

js面向对象的几种方式

时间:2016-08-16 16:01:59      阅读:198      评论:0      收藏:0      [点我收藏+]

标签:

第一种模式:工厂方式

var lev=function(){ return "脚本之家"; };

function Parent(){ var Child = new Object(); Child.name="脚本"; Child.age="4"; Child.lev=lev; return Child; };

var x = Parent();

alert(x.name);

alert(x.lev());

第二种模式:构造函数方式

var lev=function(){ return "脚本之家"; };

function Parent(){ this.name="脚本"; this.age="30"; this.lev=lev; };

var x =new Parent();

alert(x.name);

alert(x.lev());

第三种模式:原型模式

var lev=function(){ return "脚本之家"; };

function Parent(){ };

Parent.prototype.name="李小龙";

Parent.prototype.age="30";

Parent.prototype.lev=lev;

var x =new Parent();

alert(x.name);

alert(x.lev());

第四种模式:混合的构造函数,原型方式(推荐)

function Parent(){ this.name="脚本"; this.age=4; };

Parent.prototype.lev=function(){ return this.name; };

var x =new Parent();

alert(x.lev());

第五种模式:动态原型方式

function Parent(){ this.name="脚本"; this.age=4; if(typeof Parent._lev=="undefined"){

        Parent.prototype.lev=function(){ return this.name; } Parent._lev=true; }

};

var x =new Parent();

alert(x.lev());

 

js面向对象的几种方式

标签:

原文地址:http://www.cnblogs.com/luoluoweb/p/5776635.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!