【javascript 】组合式继承

开发人员采用的js的继承结构

function inheritPrototype(subType, superType) {
    var prototype = object(superType.prototype);
    prototype.constructor = subType;
    subType.prototype = prototype;
}

function obj() {
    function F() {}
    F.prototype = o;
    return new F();
}
function create(parent, test) {
    var f = obj(parent.prototype); //创建对象
    f.constructor = test; //增强对象
}
function Parent(name) {
    this.name = name;
    this.arr = ['brother', 'sister', 'parents'];
}

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

function Child(name, age) {
    Parent.call(this, name);
    this.age = age;
}
inheritPrototype(Parent, Child); //通过这里实现继承
var test = new Child('peter', 20);
test.arr.push('new');
console.log(test.arr); //brother,sister,parents,new
console.log(test.run()); //只共享了方法
var test2 = new Child('jack', 22);
console.log(test2.arr); //引用问题解决


关于call apply
call(thisObj, Object); // call接收一个对象
apply(thisObj, [argArray]) //apply接收一个数组
call和apply可以用来改变函数中this的指向: 全选复制放进笔记 // 定义一个全局函数
function f() {
    console.log(this.name);
}
// 定义一个全局变量
var name = 'peter';
var obj = {
    name: 'jack';
};
f.apply(window); //apple, 此时this 等于window  相当于window.f()
f.apply(obj);
原文地址:https://www.cnblogs.com/airven/p/5350245.html