We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
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
面试中经常会被问到,这个问题并不是很难,只是容易忘记,所以写篇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中的类继承的概念。
The text was updated successfully, but these errors were encountered:
No branches or pull requests
JavaScript中的继承
寄生式继承
原型式继承要求必须有一个对象(比如parent)作为另一个对象的基础。如果有这么一个对象的话,可以把他传递给object()函数,然后再根据具体需求对返回的对象加以修改即可。
ECMA中的Object.create()方法规范了原型式继承。Object.create()方法有两个参数,第一个参数是基础原型对象,第二个参数是一个属性描述符对象,其中描述的每一个属性都会覆盖原型对象上的同名属性。
寄生组合式继承
寄生组合式继承是实现类继承的最有效的方式,模拟OO中的类继承的概念。
The text was updated successfully, but these errors were encountered: