1、new操作符跟Object构造函数
var person = new Object(); 可以写成 var person = {};
person.name = "kitty";
person.age = 25;
2、“对象字面量”表示法
var person = {
name: "allan",
age: 18
};
3、工厂模式
var createPerson = function(name,age){
var o = new Object();
o.name = name;
o.age = age;
o.sayName = function(){
console.log(name)
};
return o;
}
var person1 = createPerson("Kitty",18);
person1.sayName();
4、构造函数
function Person(name,age){
this.name = name;
this.age = age;
this.sayName = function(){
console.log(this.name);
};
};
var person1 = new Person("Kitty",18);
person1.sayName();
网友评论