Javascript 文字与 oop 函数
使用这些的最佳实践是什么?
var x = { a: 'a', eat: function() { }, ... }
VS
var x = function() { var a = 'a'; this.eat = function() { }}
需要启动上述内容:
new x();
有人可以帮我解释一下两者的重要性吗?在 oop 社区中,哪一个是首选?任何智慧之言都会有所帮助。我也做了一些研究,但没有任何结果。深思熟虑,值得赞赏。
whats the best practice to use these?
var x = { a: 'a', eat: function() { }, ... }
vs
var x = function() { var a = 'a'; this.eat = function() { }}
the above needs to be initiated:
new x();
can someone help me explain the importance of the two, and which one is preferred choice within the oop community? any word of wisdom would help. i also did some research but nothing came up. much thought is appreciated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
基本区别在于第一个版本公开变量“a”,而第二个版本隐藏它。因此,除非您想要或需要客户端代码来访问
xa
,否则首选第二个版本。第三种方法是使用原型。在这种情况下,构造函数中的局部变量不会给您带来多大好处,因此如果
eat()
需要访问a
,那么您可以这样 写:在这种情况下,每个实例都有一个新的
a
副本,但只有一个eat
副本。缺点(如果您认为是一个)是a
可供x
实例的用户使用。The basic difference is that the first version exposes the variable 'a', while the second one hides it. So unless you want or need client code to access
x.a
, the second version is preferred.A third approach would be to use a prototype. In this case, a local variable in the constructor won't do you much good, so if
eat()
needs access toa
, then you'd write:In this case, each instance has a new copy of
a
, but there's only one copy ofeat
. The drawback (if you consider it one) is thata
is available to users ofx
instances.第一个只会创建一个对象,您不能将其与
new
关键字一起使用。第二个包含一个局部变量a
,而不是像第一个那样创建属性。函数通常被编写为命名函数,而不是分配给变量的匿名函数:
现在您可以使用它创建对象:
为对象指定方法的另一种方法是将其放入原型中:
The first one will just create a single object, you can't use it with the
new
keyword. The second one contains a local variablea
instead of creating a property like the first one.Functions are usually written as named functions instead of anonymous functions assigned to variables:
Now you can create objects using it:
Another way of specifying methods for the object is to put it in the prototype:
一般来说,这取决于您想要获得什么。请记住,JS 没有真正的类,它是基于原型的语言。运算符
new
非常具有误导性。我建议尽可能使用文字
{}
。例如,您可以这样做:如果您只需要一个实例,则始终可以在定义该函数后立即调用该函数。
但是如果你想使用原型,使用构造函数可能会更容易 - 但我仍然不会按原样使用 new 运算符,也许将其包装在其他函数中会更好。
Generally it depend on what you are trying to get. Remember, that JS has no real classes, its prototype based language. Operator
new
is quite misleading.I would suggest using literal
{}
whenever it is possible. In example, you could do it like this:If you want only one instance, you could always call this function just after defining it.
BUT if you want to use
prototype
, it could be easier with Construction function - but still, i wouldn't use new operator as is, maybe wrapping it in some other func would be better.