到目前为止,我看到了用JavaScript创建对象的三种方法。哪种方法最适合创建对象,为什么?
我还看到在所有这些示例中,var
在属性之前未使用关键字-为什么?var
提到属性是变量时,是否不必在属性名称之前声明?
在第二和第三种方式中,对象的名称为大写,而在第一种方式中,对象的名称为小写。我们应该在什么情况下使用对象名称?
function person(fname, lname, age, eyecolor){
this.firstname = fname;
this.lastname = lname;
this.age = age;
this.eyecolor = eyecolor;
}
myFather = new person("John", "Doe", 50, "blue");
document.write(myFather.firstname + " is " + myFather.age + " years old.");
var Robot = {
metal: "Titanium",
killAllHumans: function(){
alert("Exterminate!");
}
};
Robot.killAllHumans();
var NewObject = {};
NewObject['property1'] = value;
NewObject['property2'] = value;
NewObject['method'] = function(){ /* function code here */ }
没有最好的方法,这取决于您的用例。
Person
(您应使用大写字母开头名称)称为构造函数。这类似于其他OO语言中的类。更新:如第三种方式要求的示例。
相关属性:
下列情况不上班this
也没有参考book
。无法使用对象文字中的其他属性的值来初始化属性:
var book = {
price: somePrice * discount,
pages: 500,
pricePerPage: this.price / this.pages
};
相反,您可以执行以下操作:
var book = {
price: somePrice * discount,
pages: 500
};
book.pricePerPage = book.price / book.pages;
// or book['pricePerPage'] = book.price / book.pages;
动态属性名称:
如果属性名称存储在某个变量中或通过某个表达式创建,则必须使用方括号表示法:
var name = 'propertyName';
// the property will be `name`, not `propertyName`
var obj = {
name: 42
};
// same here
obj.name = 42;
// this works, it will set `propertyName`
obj[name] = 42;
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句