Javascript中类和对象之间的区别 [英] Difference between a class and an object in Javascript
问题描述
有什么区别
var myView = function () {
//something goes here
};
和
var myView = function () {
//something goes here
return {
a: x,
b: y
}();
我认为第一个片段创建了一个动态类,所以你可以说
I think the first snippet creates a "dynamic" class, so that you can say
var anotherView = new myView();
和第二个片段类似于单个动态对象,但我不是很确定。
and the second snippet is similar to a singleton "dynamic" object, but I'm not very sure.
推荐答案
Javascript使用原型继承,因此 本身没有类。一切都是一个对象;只是某些对象有一个共同的父对象,当名称解析查找原型链时,会找到其方法/变量。
Javascript uses prototypal inheritance, so there are no classes per se. Everything is an object; it's just that some objects have a common parent object whose methods/variables will be found when name resolution looks up the prototype chain.
你的第一个代码片段会创建一个名为<的对象code> myView 其类型是一个函数。你的第二个片段定义了一个匿名方法,它返回一个对象(有两个属性, a
和 b
),然后立即调用此方法,将结果分配给 myView
。所以在第二种情况下, myView
是一个具有两个自定义属性的对象。
Your first code snippet creates an object called myView
whose type is a function. Your second snippet defines an anonymous method which returns an object (with two properties, a
and b
) and then immediately calls this method, assigning the result to myView
. So in this second case, myView
is an object with two self-defined properties.
它可能对你有所帮助阅读道格拉斯·克罗克福德关于 Javascript原型继承的描述,因为听起来你有点模糊细节。
It may help you to read Douglas Crockford's description of prototypal inheritance in Javascript, as it sounds like you're a little fuzzy on the details.
这篇关于Javascript中类和对象之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!