JavaScript 有多种方式实现继承,下面这些大家哪种用的比较多,还有没有其它方式?
ES6 引入的 class 是不是最佳实践呢? ES5 时代,大家都用什么方式?
组合 /模块模式的方式是不是可以作为继承的替代?
请大家指导,各抒己见。
function SuperClass(p) {
this.prop = p
this.method = function () {return this.prop}
}
function SubClass(p2) {
this.prop2 = p2
this.method2 = function () {return this.prop2}
}
SubClass.prototype = new SuperClass('prop') // inherit/extends
let so = new SubClass('prop2') // create instance
console.log(so.method())
console.log(so.method2())
let SuperObject = {
prop: 'prop',
method: function () {
return this.prop
}
}
let SubObject = Object.create(SuperObject) // equals to inheritance/extension
let so = Object.assign(SubObject, { // equals to instantiation
prop2: 'prop2',
method2: function () {
return this.prop2
}
})
console.log(so.method())
console.log(so.method2())
let SuperObject = {
prop: 'prop',
method: function () {
return this.prop
}
}
let SubObject = {
prop2: 'prop2',
method2: function () {
return this.prop2
}
}
let so = Object.setPrototypeOf(SubObject, SuperObject) // equals to inheritance/extension, and equals to instantiation also
console.log(so.method())
console.log(so.method2())
class SuperClass {
constructor(p) {
this.prop = p
}
method() {
return this.prop
}
}
class SubClass extends SuperClass { // inherit/extends
constructor(p2) {
super('prop')
this.prop2 = p2
}
method2() {
return this.prop2
}
}
let so = new SubClass('prop2') // create instance
console.log(so.method())
console.log(so.method2())
let SuperClass = {
createNew: function (p) {
let prop = p
let o = {}
o.method = function () {
return prop
}
return o
}
}
let SubClass = {
createNew: function (p2) {
let prop2 = p2
let o = SuperClass.createNew('prop') // equals to inheritance/extension, you can use composition also
o.method2 = function () {
return prop2
}
return o
}
}
let so = SubClass.createNew('prop2') // equals to instantiation
console.log(so.method())
console.log(so.method2())
这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。
V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。
V2EX is a community of developers, designers and creative people.