【发布时间】:2015-12-19 20:21:32
【问题描述】:
我有 3 个代码:
var control = new Control();
function Control() {
this.doSomethingElse = function() {...}
this.doSomething = function () {
control.doSomethingElse();
}
}
或者
var control = new Control();
function Control() {
var self = this;
this.doSomethingElse = function() {...}
this.doSomething = function () {
self.doSomethingElse();
}
}
或者
var control = Control();
function Control() {
var self = this;
this.doSomethingElse = function() {...}
this.doSomething = function () {
self.doSomethingElse();
}
return self;
}
重要:该函数是一个控制器,并且只声明了一次。然后我在我的代码中到处使用“控制”......
我想知道 control.doSomethingElse() 是否很慢?
最后,在这些示例中,什么是正确的做法和/或最快的代码?
谢谢!
【问题讨论】:
-
#1 是错误的 - 对象永远不应该在内部使用外部已知的名称。这就是
this(或self)的用途。 -
@Alnitak:他正在使用单例对象。看起来他根本不需要构造函数。
-
@squint true,但在这种情况下,他不应该在作业中使用
this- 只需function Control() { return { doSomethingElse: ..., doSomething: ... } }
标签: javascript this declare