【问题标题】:What OOP in Javascript should look like?Javascript 中的 OOP 应该是什么样的?
【发布时间】:2012-06-14 16:33:03
【问题描述】:

我正在使用 Jquery 编写一段较长的代码,众所周知,这似乎是一个简单的项目,随着复杂性的增加,现在看起来就像一个无法管理的意大利面条,功能和代码到处重复。因此,我开始将所有功能倾倒在这样的对象上:

function MyObject(container) {
    this.container = container
};

Notifications.prototype.featureOne = function (arg1, arg2){

};

Notifications.prototype.featureTwo = function (arg1, arg2, arg3){

};

obj1 = new Notifications($('#container'));
obj1.featureOne('arg1', 'arg2');
obj1.featureOne('arg1', 'arg2', 'arg3');

显然,这使得知道发生了什么变得非常简单,但我注意到我有一些与另一个非常相似的代码(特别是,一个接受 2 个参数的 ajax 函数和另一个接受与以前相同的 2 个参数的 ajax 函数加上一个额外的一)。我能做些什么?创建一个新的原型方法来创建一个函数来包装这两种情况?

另一个问题:在 Javascript 中处理 OOP 时,您使用了哪些最佳实践?

谢谢!

【问题讨论】:

  • 如果您想查看一些正确的代码,请转到 coffeescript.org -> "Try CoffeeScript" 并输入 class Foo \n\n class Bar extends Foo(将 \n 替换为换行符) - 但它可能是有点难以理解。
  • 抱歉,我不知道 CoffeeScript,所以现在对我帮助不大。

标签: javascript oop


【解决方案1】:

原型继承是这样工作的。假设你有一个“班级”。

// original "class"
var SomeObject = function( constructorArg1 ) {
   this.someProperty = constructorArg1;
};
SomeObject.prototype.method1 = function( arg1, arg2 ) {
   // some code
};

现在假设您要创建一个继承方法 1 的类,但还要添加更多内容。

// new "class" which inherits from first "class"
var SomeOtherObject = function( constructorArg1 ) {
   this.someProperty = constructorArg1;
};
// inheritance happens here
SomeOtherObject.prototype = new SomeObject();
// must also set the constructor as part of prototypical inheritance
SomeOtherObject.prototype.constructor = SomeOtherObject;
// add a second method to your new "class"
SomeOtherObject.prototype.method2 = function( arg1 ) {
   // some code
};

你会看到这个系统并不完美,因为它不允许你继承原来的构造函数,并且如果父类方法被覆盖,你不能调用它们,但是所有方法都添加到第一个“类”的原型中"现在在新的“类”中可用。

大约有 100 种方法可以使用这个想法来模拟经典继承,并且几乎可以设置它的工作方式,能够从扩展类中调用覆盖的父方法等。许多方法模拟经典继承根本不使用原型继承,而只是简单地将方法从一个原型复制到另一个原型。您将不得不进行一些搜索或试验,以了解最适合您的方法。

【讨论】:

  • 不应该是SomeOtherObject.prototype.constructor = SomeOtherObject;
猜你喜欢
  • 2013-07-17
  • 2012-01-05
  • 2015-12-09
  • 2017-12-14
  • 1970-01-01
  • 1970-01-01
  • 2013-10-31
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多