2016-07-30 45 views
0

我在閱讀關於面向對象的JS,但在傳統的面向對象和麪向對象之間混淆了。而且我在github中也發現很多很棒的JS項目都沒有寫成'OOP方式'。他們利用對象腸胃模式,如揭示模式和單身。我來自Java,現在我在下面的模式之間,以及何時使用它們。什麼時候使用這個,而不是JavaScript中的對象字面值?

OOP:

function cook(){ 
this.vege = 'something'; 
} 

var Cook = new cook(); 
console.log(Cook.vege = 'something else') 

對戰對象字面方式:

var cook = { 

vege:"something" 

} 
cook.vege = "something else" 

回答

0

比方說,有一個特定的學生創建100個對象:

var Student = function (name) { 
 
    this.name = name; 
 
    this.greet = function() { 
 
    console.log("My name is " + this.name); 
 
    }; 
 
}; 
 

 
var praveen = new Student("Praveen Kumar"); 
 
var hello = new Student("Hello, World!"); 
 
var jeff = new Student("Jeff Atwood"); 
 

 
praveen.greet(); 
 
hello.greet(); 
 
jeff.greet();

但是,如果我突然想喜歡greet()功能增加另一個功能是什麼:

console.log("Hola! This is " + this.name); 

的現在的「類」就派上用場了。

var Student = function (name) { 
 
    this.name = name; 
 
    this.greet = function() { 
 
    console.log("My name is " + this.name); 
 
    }; 
 
}; 
 

 
var praveen = new Student("Praveen Kumar"); 
 
var hello = new Student("Hello, World!"); 
 
var jeff = new Student("Jeff Atwood"); 
 

 
Student.prototype.sayHola = function() { 
 
    console.log("Hola! This is " + this.name); 
 
}; 
 

 
praveen.sayHola(); 
 
hello.sayHola(); 
 
jeff.sayHola();

很容易在一個單一的原型加比不斷增加的所有對象。這將該功能添加到所有對象。

1

通常,您只需要一個對象文字。但是,如果您想要使用相同的模式創建多個對象實例,則應該使用構造函數來避免重複自己。

function Cook(name) { 
    this.name = name; 
    this.vege = 'something'; 
} 

Cook.prototype = { 
    cookSomething: function() { ... }, 
    doDishes: function() { ... } 
}; 

現在你可以做:如果你想分享的東西,類似的方法,跨實例,這也是很重要

var fred = new Cook('Fred'); 
var lisa = new Cook('Lisa'); 

...他們都會有一個cookSomethingdoDishes方法。