可能重复:
了解JavaScript中的原型继承
好的,所以我对JS中的OOP概念有些新意.
这两个代码片段之间有什么区别:
function animal(){
this.name = 'rover';
this.set_name = function(name){
this.name = name;
}
}
Run Code Online (Sandbox Code Playgroud)
function animal(){
this.name = 'rover';
}
animal.prototype.set_name = function(name){
this.name = name;
}
Run Code Online (Sandbox Code Playgroud)
他们都做同样的事情,那有什么区别?
我喜欢返回构造函数的模块模式,如下所述:http: //elegantcode.com/2011/02/15/basic-javascript-part-10-the-module-pattern/
但是我不确定如何从使用此模式实现的对象继承.假设我实现了一个父对象...
namespace('MINE');
MINE.parent = (function() {
// private funcs and vars here
// Public API - constructor
var Parent = function (coords) {
// ...do constructor stuff here
};
// Public API - prototype
Parent.prototype = {
constructor: Parent,
func1: function () { ... },
func2: function () { ... }
}
return Parent;
}());
Run Code Online (Sandbox Code Playgroud)
我如何定义一个子对象,它也使用继承的模块模式,parent
例如,我可以有选择地覆盖func2
?