2017-02-15 90 views
1

我正在编写一些JavaScript类(旧学校,不使用ES2015/ES6,我不想使用Babel或其他转换器),并且我有一个继承另一个,覆盖其中一个父方法。对原型类使用对象文字

所以,我有我的初步App.Hello类:

var App = {}; 
App.Hello = function(args) { 
    this.name = args.name; 
} 
App.Hello.prototype = { 
    constructor: App.Hello, 
    sayHello: function() { 
     console.log('Hello, ' + this.name); 
    }, 
    sayGoodbye: function() { 
     console.log('Goodbye, ', this.name); 
    } 
} 

的然后我App.Yo类从它继承:

// inherits from App.Hello 
App.Yo = function(args) { 
    App.Hello.call(this, args); 
} 
App.Yo.prototype = Object.create(App.Hello.prototype); 
App.Yo.prototype = { // want to combine this with above! 
    constructor: App.Yo, 
    sayHello: function() { 
     console.log('Yo, ', this.name); 
    } 
} 

但是因为我使用对象字面结构我改写的原型App.Yo当我通过它constructorsayHello方法后设置Object.create。所以我没有从App.Hello继承sayGoodby方法

1.我怎样才能解决这个问题,但使用文字结构?

我知道我可能只是这样做:

App.Yo.prototype = Object.create(App.Hello.prototype); 
App.Yo.prototype.constructor = App.Yo; 
App.Yo.prototype.sayHello = function sayHello() { 
    console.log('Yo, ', this.name); 
} 

但我想保持字面结构,我的课将会有很多在他们不同的方法。所以想保持它的漂亮和整洁。

2.是否可以将整个类嵌套为文字?那么构造函数也嵌套为文字的一部分吗?

例如

App.Hello = function(args) { 
    this.name = args.name; 
} 

App.Yo = function(args) { 
    App.Hello.call(this, args); 
} 

回答

1
  1. 我怎样才能解决这个问题,但使用文字结构?

使用Object.assign,这是在ES2015添加,但它可以polyfilled所以你不必transpile:

App.Yo.prototype = Object.assign(Object.create(App.Hello.prototype), { 
    constructor: App.Yo, 
    sayHello: function() { 
     console.log('Yo, ', this.name); 
    } 
}); 

或者,如果你不想填充工具,只需用自己的助手,像标准extend功能(jQuery有一个叫$.extend,像许多其他工具库):

function extend(target) { 
    var i, source; 
    for (i = 1; i < arguments.length; ++i) { 
     source = arguments[i]; 
     Object.keys(source).forEach(function(name) { 
      target[name] = source[name]; 
     }); 
    } 
    return target; 
} 

App.Yo.prototype = extend(Object.create(App.Hello.prototype), { 
    constructor: App.Yo, 
    sayHello: function() { 
     console.log('Yo, ', this.name); 
    } 
}); 
  1. 是否可以将整个类嵌套为文字?

是的,通过进一步辅助功能。例如:

function derive(base, props) { 
    var cls = function() { 
     return base.apply(this, arguments); 
    }; 
    cls.prototype = Object.create(base.prototype); 
    Object.assign(cls.prototype, props); // Or use your `extend` here 
    return cls; 
} 

App.Yo = derive(App.Hello, { 
    constructor: App.Yo, 
    sayHello: function() { 
     console.log('Yo, ', this.name); 
    } 
}); 

当然,也有很多你在Yo与使用该参数的功能从缺,就像控制传递到Hello

如果你想进一步探索,你可以看看我的Lineage library,这使得在ES5中创建类,并且以前是相当简单和声明性的。就我个人而言,我认为它已经过时了,因为ES2015和transpiling,但你已经说过你不想使用一个transpiler ...