您的位置:首页 > Web前端 > JavaScript

JavaScript2种构造函数创建对象的模式以及继承的实现

2015-06-07 12:25 1161 查看
第一种模式:

function Person(){
}
Person.prototype.say=function(){
    alert('hello');
}
var person=new Person();
person.say();//hello


根据第一种模式说一下继承的实现:

function Person(){
}
Person.prototype.say=function(){
    alert('hello');
}
function Man(){}
Man.prototype=new Person()
var man=new Man();
man.say(); //hello


第二种模式:

function Person(){
    var _this={};//创建一个空的对象
    _this.say=function(){alert('hello')};
    return _this;
}
function person=new Person();
person.say();//hello


第二种模式的继承:

function Person(){
    var _this={};//创建一个空的对象
    _this.say=function(){alert('hello')};
    return _this;
}
function Man(){
    var _this=new Person();
    return _this;
}
var a=new Man();
a.say();//hello


本文作者:罗坚元
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: