类继承模式

/**
 * 来自<<javascript 模式>>
 *
 * 本人学习时整理了一遍
 */

/**
 * 类继承模式-默认模式
 */

function inherit (C, P) {
    C.prototype = new P;
}

//父构造函数
function Parent(name) {
    this.name = name || "Adam";
}

//往父类构造函数的原型上添加一个方法
Parent.prototype.say = function() {
    return this.name;
}

//子类构造函数
function Child(name) {
    this.name = name;
}

inherit(Child, Parent);

var cd = new Child('Tina');
console.log(cd.say());
/**
 * 类继承模式-借用构造函数
 * 该模式只能继承父类构造函数中添加到this的属性,不能继承来自原型的属性和静态属性。
    //实现构造函数继承的核心方法
    function Child(name) {
        Parent.apply(this, arguments);
        this.name = name;
    }
 */

//父构造函数
function Article() {
    this.tags = ['js', 'css'];
}

var article = new Article();

function BlogPost() {}
BlogPost.prototype = article;

var blog = new BlogPost();

function StaticPage() {
    Article.call(this, arguments);
}

var page = new StaticPage();


console.log(article.hasOwnProperty('tags'));
console.log(blog.hasOwnProperty('tags'));
console.log(page.hasOwnProperty('tags'));

//借用构造函数实现多重继承
function Cat() {
    this.legs = 4;
    this.say = function() {
        return "meaowww";
    }
}

function Bird() {
    this.wings = 2;
    this.fly = true;
}

function CatWings() {
    Cat.apply(this);
    Bird.apply(this);
}

var jane = new CatWings();

console.dir(jane);
/**
 * 借用父类的构造函数,并设置子类的原型属性,实现近乎最接近传统继承的摸型.
 * 当然,在javascript会带来其它的问题。
 */

function Parent(name) {
    this.name = name || "Adam";
}

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

function Child(name) {
    //借用构造函数
    Parent.apply(this,arguments);
}
//设置原型
Child.prototype = new Parent();

var kid = new Child('mtima');
console.log(kid.name);
console.log(kid.say());
/**
 * 类继承模式-临时构造函数
 * 这可以避免默认模式带来的父类this上的属性问题
 * 更安全,效率也更高
 */

function inherit(C,P) {
    var F = function() {}
    F.prototype = P.prototype;
    C.prototype = new F;
    /**
     * 我们还可以设置一个指向父类prototype的引用
     * 实现类似php中调用父类的parent关键字的功能
     */
    C.uper = F.prototype;
}
//父构造函数
function Parent(name) {
    this.name = name || "Adam";
}

//往父类构造函数的原型上添加一个方法
Parent.prototype.say = function() {
    return this.name;
}

Parent.prototype.getAge = function() {
    return this.age;
}

//子类构造函数
function Child(age) {
    this.age = age;
}

//实现临时构造函数
inherit(Child, Parent);

var kid = new Child(20);
console.log(kid.name);
console.log(kid.say());
console.log(kid.getAge());
原文地址:https://www.cnblogs.com/mtima/p/3187664.html