javascript创建 对象常用方式
1.工厂模式
function Person(name, age, job){
var o = new Object();
o.name = name;
o.age = age;
o.job = job;
o.sayName = function(){
alert(this.name);
};
return o;
}
var person = Person("Greg", 27, "Doctor");
person.sayName();// Greg
工厂模式虽然解决了创建多个相似对象的问题,但却没有解决对象识别的问题(即不能知道一个对象的类型)
2.构造函数模式
function Person(name, age, job){
this.name = name;
this.age = age;
this.job = job;
this.sayName = function(){
alert(this.name);
};
}
var person = new Person("Greg", 27, "Doctor");
person.sayName();// Greg
构造函数始终都应该以一个大写字母开头,而非构造函数则应该以一个小写字母开头
3.原型模式
function Person(){
}
Person.prototype.name = "Nicholas";
Person.prototype.age = 29;
Person.prototype.job = "Software Engineer";
Person.prototype.sayName = function(){
alert(this.name);
};
var person = new Person();
person.sayName();//Nicholas
对于原型模式理解就是,每个函数都有一个 prototype(原型)属性,这个属性是一个指针,指向一个对象, 而这个对象的用途是包含可以由特定类型的所有实例共享的属性和方法。
4.直接创建一个 Object 的实例
var person = new Object();
person.name = "Nicholas";
person.age = 29;
person.job = "Software Engineer";
person.sayName = function(){
alert(this.name);
};
person.sayName();//Software Engineer
5.通过”字面量“方式创建
var person = {
name: "Nicholas",
age: 29,
job: "Software Engineer",
sayName: function(){
alert(this.name);
}
};
person.sayName();//Nicholas
6.定义 class 类的方式
class Person{
constructor(name,age){
this.name = name;
this.age = age;
}
sayName(){
alert(this.name)
}
};
var person = new Person('Nicholas');
person.sayName();//Nicholas