关闭

javascript中的继承

133人阅读 评论(0) 收藏 举报

一)对象冒充方式

function Father(username) {
    this.username = username;
    this.sayName = function() {
        alert(this.username);
    };
}

function Son(username, password) {
    this.method = Father;
    this.username(username);
    delete this.method;// 关键

    this.password = password;
    this.sayPassword = function() {
        alert(this.password);
    };
}

var father = new Father('papa');
var son = new Son('bab', '123');
father.sayName();
son.sayName();
son.sayPassword();

二)Call方法方式:call方法是function对象中的方法,因此我们定义的每个函数都有该方法,通过函数名来调用该方法,call方法的第一个参数会被传递给函数中的this,从第二个参数开始,逐一赋值给函数中的参数

function Father(username) {
    this.username = username;
    this.sayName = function() {
        alert(this.username);
    };
}

function Son(username, password) {
    Father.call(this, username);
    this.password = password;
    this.sayPassword = function() {
        alert(this.password);
    };
}

三)Apply方法方式

function Father(username) {
    this.username = username;
    this.sayName = function() {
        alert(this.username);
    };
}

function Son(username, password) {
    Father.apply(this, new Array(username));
    this.password = password;
    this.sayPassword = function() {
        alert(this.password);
    };
}

四)原型链方式

function Father() {
}
Father.prototype.hello = "hello";
Father.prototype.sayHello = function() {
    alert(this.hello);
};

function Son() {
}
Son.prototype = new Father();
Son.prototype.world = "world";
Son.prototype.sayWorld = function() {
    alert(this.world);
};

var son = new Son();
son.sayHello();
son.sayWorld();

五)混合方式(推荐)

function Father(hello) {
    this.hello = hello;
}
Father.prototype.sayHello = function() {
    alert(this.hello);
};

function Son(hello, world) {
    Father.call(this, hello);
    this.world = world;
}
Son.prototype = new Father();
Son.prototype.sayWorld = function() {
    alert(this.world);
};

var son = new Son('hello', 'world');
son.sayHello();
son.sayWorld();



0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:9041次
    • 积分:135
    • 等级:
    • 排名:千里之外
    • 原创:3篇
    • 转载:20篇
    • 译文:0篇
    • 评论:0条
    文章存档