声明javascript对象与var与函数之间有什么区别? [英] What is the difference between declaring javascript objects with var vs. with function?
本文介绍了声明javascript对象与var与函数之间有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我是个混乱的新手。我在一个教程中读到了你创建一个JavaScript对象,如下所示:
I'm a confused newbie. I read in a tutorial that you create a javascript object like so:
function myObject() {
this.myProperty = "a string";
this.myMethod = function () {
//Method code
}
}
然后我在其他地方读过你创建一个对象,如下所示:
Then I read somewhere else that you create an object like so:
var myObject = {
myProperty: "a string",
myMethod : function () {
//Method code
}
}
两者之间的(非主观)区别是什么?是否有正确的方法和错误的方法?
What is the (non-subjective) difference between the two? Is there an official right way and a wrong way?
推荐答案
两个声明都是正确的,但它们有不同的语义。
Both declarations are correct but they have different semantics.
第一种类型的声明允许您创建对象的实例:
The first type of declaration allows you to create instances of your objects:
var t = new myObject();
// then use t
t.myProperty = "some value";
var otherT = new myObject();
otherT.myProperty = "some other value";
第二个几乎就像一个静态对象:
The second is almost like a static object:
myObject.myProperty = "some value";
这篇关于声明javascript对象与var与函数之间有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文