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