javascript 对象字面量 vs 构造函数+原型
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17260603/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Object literal vs constructor+prototype
提问by HIRA THAKUR
Object literal=name value pairs wrapped in curly braces.
用花括号括起来的对象字面量= 名称值对。
Constructor=a function used to create multiple instance using keyword new.
构造函数= 用于使用关键字 new 创建多个实例的函数。
Prototype=for extension of a literal.
原型= 用于文字的扩展。
This is what I have understood till now.But the more I research,More I get confused about what is the significanceof each one of them. I have used constructor,protoypes and literalsin my code a few times.But everytime I use them,I feel like I am still not aware of the full potential of it.I want to go one step ahead of being a begineer now.I hope Folks at stackoverflow help me achieve it
这是我迄今为止所理解的。但是我研究得越多,我就越对它们中的每一个的意义感到困惑。我在我的代码中使用了几次构造函数、原型和文字。但是每次我使用它们时,我觉得我仍然没有意识到它的全部潜力。我现在想比初学者更进一步。我希望 stackoverflow 的人帮助我实现它
Which is the bestpreferred way of programming(object literals vs constructors vs prototype)
can a code with constructor and protoype be written using just object literals withoutusing constructor and protoype.
what is the signifiance of anonymous function.
哪种编程方式最好(对象字面量 vs 构造函数 vs 原型)
可以只使用对象文字而不使用构造函数和原型来编写带有构造函数和原型的代码 吗?
匿名函数的意义是什么。
A very simple example demonstrating their importance will also do.I am aware of what they are but I am not aware of what possible magic they can do.
一个非常简单的例子也可以证明它们的重要性。我知道它们是什么,但我不知道它们可以做什么。
采纳答案by Niccolò Campolungo
There is a (fundamental, in my opinion) difference between object literals and functions, the "private" variables. Since an object can't be instantiated(because it is already an instance of Object
) it has no possibility to have its own (new) scope. It is a base concept of advanced JS programming. Having a new scope allows you to do almost everything(you can declare your own window
, document
or whatever you want except the JS keywordsinside your own scope). Now, some simple examples:
对象文字和函数之间存在(在我看来是根本的)差异,即“私有”变量。由于对象无法实例化(因为它已经是 的实例Object
),因此不可能拥有自己的(新)范围。它是高级 JS 编程的基本概念。拥有一个新的范围可以让你做几乎所有的事情(你可以声明你自己的window
,document
或者你想要的任何东西,除了你自己的范围内的 JS关键字)。现在,一些简单的例子:
Let's assume you want to create a large number of instances of the same object(using as few lines as possible):
假设您想为同一对象创建大量实例(使用尽可能少的行):
function MyObj(i) {
var privateCounter = "I am the instantiated object " + i + " .";
this.counter = function() {
return privateCounter;
};
}
var MyObjList = [],
ObjLitList = [];
for (var i = 0; i < 100; i++) {
MyObjList.push(new MyObj(i));
ObjLitList.push({counter: "I am the literal object number " + i + "."});
}
Now you have 200 objects that are almost, but not precisely, the same thing. You can extend them as you prefer, because functions areobjects, but in the case of the function you cannot access the private
variable directly. Let's see which are the advantages of a function:
现在您有 200 个几乎但不完全相同的对象。您可以根据需要扩展它们,因为函数是对象,但在函数的情况下,您不能private
直接访问变量。让我们看看函数有哪些优点:
- It is treated like an
Object
- It has its own
Prototype
- It has private variables
- 它被视为
Object
- 它有自己的
Prototype
- 它有私有变量
And the Object
s?
而Object
s?
- It isan
Object
- It doesn't have its own
Prototype
, but you can declare the functions and extend the object itself - It doesn't have private variables
- 它是一个
Object
- 它没有自己的
Prototype
,但您可以声明函数并扩展对象本身 - 它没有私有变量
Apart the private vars, they are not much different from each other.
除了私有变量,它们彼此之间没有太大区别。
Let's see what a function's prototype can do:
让我们看看函数的原型可以做什么:
MyObj.prototype.setX = function(x) {
this.x = x;
}
Using the prototype allows you to create an only instance of an anonymous function(which can be named too and then assigned) which will be shared across instances. How can you do the same thing with object literals?
使用原型允许您创建匿名函数的唯一实例(也可以命名然后分配),该实例将在实例之间共享。你怎么能用对象字面量做同样的事情?
function setX(x) {
this.x = x;
}
var obj = {
setX: setX
};
As you can see you have to create the object defining everytime a property which is setX
. Otherwise, you can extend Object.prototype
itself(but there is a long debate about extending the prototype of native JS objects).
如您所见,您必须创建对象,每次定义一个属性为setX
. 否则,您可以扩展Object.prototype
自身(但关于扩展原生 JS 对象的原型存在长期争论)。
So which is the bestway? There is no one, it depends on what you have to do, what you need from your script, which of the two you feel more comfortable with.
那么最好的方法是什么?没有一个,这取决于你必须做什么,你需要从你的脚本中得到什么,你觉得两者中的哪一个更舒服。
I prefer writing my own functions and treat them like classes, because they are more readable and I am able to use "private" variables. I don't know anyone using literals instead of functions though.
我更喜欢编写自己的函数并将它们视为类,因为它们更具可读性并且我能够使用“私有”变量。我不知道有人使用文字而不是函数。
As for the questions:
至于问题:
Which is the best preferred way of programming(object literals vs constructors vs prototype)
哪种编程方式最好(对象字面量 vs 构造函数 vs 原型)
Answered.
回答。
can a code with constructor and protoype be written using just object literals without using constructor and protoype.
可以只使用对象文字而不使用构造函数和原型来编写带有构造函数和原型的代码吗?
Yes, you can if you don't need private variables(and if the script isn't too big. Imagine jQuery written as an Object literal :D).
是的,如果你不需要私有变量,你可以(如果脚本不是太大。想象一下 jQuery 写成一个对象文字 :D)。
what is the signifiance of anonymous function.
匿名函数的意义是什么。
Oh well, I can answer with an example:
哦,好吧,我可以用一个例子来回答:
//code
myNamedFunction();
//code
function myNamedFunction() {
alert("I'm defined everywhere! :)");
}
This works and won't generate a TypeError
.
这有效并且不会生成TypeError
.
myAnonymousFunction();
var myAnonymousFunction = function() {
alert("I'm defined after this declaration :(");
}
myAnonymousFunction(); // works!
This will cause a Uncaught TypeError: undefined is not a function
, because myAnonymousFunction
is only a referenceto the effective function(which is unnamed, so it is not callable from the script).
这将导致 a Uncaught TypeError: undefined is not a function
, 因为myAnonymousFunction
它只是对有效函数的引用(未命名,因此无法从脚本中调用)。
There are a lot of things to say about this argument, and a good point to start advanced programming is Javascript Garden. Other good readings are Basics of OOP in JS - NetTutsPlus, Working with Objects - MDNand OOP in JS - Phrogz
关于这个论点有很多话要说,开始高级编程的一个好点是Javascript Garden。其他不错的读物是JS 中的 OOP 基础 - NetTutsPlus,使用对象 - MDN和JS 中的 OOP - Phrogz
Hope this helps!
希望这可以帮助!
Sidenote: functions also have a good advantage since they can change their context(this
) just with a function(call
for example), while objects can't.
旁注:函数也有一个很好的优势,因为它们可以this
仅使用函数(call
例如)更改它们的上下文(),而对象则不能。