javascript中的继承

一)对象冒充方式

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();



阅读更多
个人分类: javascript
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

不良信息举报

javascript中的继承

最多只允许输入30个字

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭