我想用 JavaScript 进行简单的经典继承。我只需要子类和方法重写,而不需要prototype.js 或其他一些库提供的冗长语法和花里胡哨的东西。
现在,这个名叫 Shelby S. Moore 的人提出了一个解决方案,它的工作方式正是我想要的: http://www.coolpage.com/developer/javascript/Correct%20OOP%20for%20Javascript.html
唯一的问题是他正在扩展 native 类型对象和函数,这破坏了我使用的一些库。另外,作为一般观察,我不想弄乱 native 对象的原型(prototype)。
我在这里制作了 Shelby S. Moore 的示例: http://jsfiddle.net/christian1974/CEKL5/
正如您从示例中看到的,它按预期工作。 现在,值(value) 64.000 美元的问题是:你能推荐一种在不干扰 Object.prototype 和 Function.prototype 的情况下使其工作的方法吗?
我正在寻找一种非常简单的语法,例如:
Extend(parent, this);
我是否应该放弃整个想法并使用现有的库来实现此目的?我是否让自己的生活变得太困难了?
最佳答案
为什么不直接创建一个函数inherits
,而不是增加对象原型(prototype)呢?
function inherits(parent)
{
//just make sure this doesn't get called on the global object (like a regular function)
//and the parent is an actual constructor reference
if (this === window || typeof parent !== 'function')
{
throw new Error('inherit not possible on window/without constructor');
}
//to set the constructor dynamically and secure the constructor of child object
//I'd say this should do the trick (be weary though, not tested)
var constr, Proto;
constr = this.constructor;
Proto = typeof parent === 'function' ? new parent : parent;//get instance
this.prototype = Proto.prototype;
this.constructor = constr;//restore constructor when needed
if( arguments.length > 1 )
{
return parent.apply( this, Array.prototype.slice.call( arguments, 1 ) );
}
return parent.call( this );
}
function Foo(someArg)
{
inherits.apply(this,[Bar,someArg]);
}
话虽如此,我并没有真正看到这种方法相对于 Object.create
和 - 因为你使用的是 libs- jQuery 的 .extend
的好处> 方法
关于JavaScript 子类化和方法重写,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11859414/