Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

JavaScript中的继承 #3

Open
ustccjw opened this issue Oct 18, 2014 · 0 comments
Open

JavaScript中的继承 #3

ustccjw opened this issue Oct 18, 2014 · 0 comments
Labels

Comments

@ustccjw
Copy link
Owner

ustccjw commented Oct 18, 2014

JavaScript中的继承

面试中经常会被问到,这个问题并不是很难,只是容易忘记,所以写篇blog记录下。
其实主要分为寄生式继承和寄生组合式继承。

寄生式继承

function object(o) {
    function F () {}
    F.prototype = o;
    return new F();
}

function getChild(parent) {
    var child = object(parent);
    child.sayHi = function () {
        console.log(this.name);
    }
    return child;
}

var parent = {
    name: 'ustccjw',
    friends: ['Alice', 'Bob']
}
var child = getChild(parent);
child.sayHi();

原型式继承要求必须有一个对象(比如parent)作为另一个对象的基础。如果有这么一个对象的话,可以把他传递给object()函数,然后再根据具体需求对返回的对象加以修改即可。
ECMA中的Object.create()方法规范了原型式继承。Object.create()方法有两个参数,第一个参数是基础原型对象,第二个参数是一个属性描述符对象,其中描述的每一个属性都会覆盖原型对象上的同名属性。

寄生组合式继承

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

function SuperType(name) {
    this.name = name;
    this.friends = ['Alice', 'Bob']
}

SuperType.prototype.sayName = function () {
    console.log(this.name);
}

function SubType(name, age) {
    SuperType.call(this, name);
    this.age = age;
}

inheritPrototype(SubType, SuperType);

寄生组合式继承是实现类继承的最有效的方式,模拟OO中的类继承的概念。

@ustccjw ustccjw added the blog label Aug 27, 2015
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant