到目前为止,我看到了三种在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.");
Run Code Online (Sandbox Code Playgroud)
var Robot = {
metal: "Titanium",
killAllHumans: function(){
alert("Exterminate!");
}
};
Robot.killAllHumans();
Run Code Online (Sandbox Code Playgroud)
var NewObject = {};
NewObject['property1'] = value;
NewObject['property2'] = value;
NewObject['method'] = function(){ /* function code here */ …Run Code Online (Sandbox Code Playgroud)