2013-12-14 53 views
1

尤其是'this'關鍵字。像下面的代碼一樣,使用函數,我可以避免重複代碼。我閱讀的樣本代碼越多,我就越困惑,就像事情可以通過這種方式實現,但還有其他(複雜的)方法可以實現它。或者我錯了?對象和函數的用法混淆javascript

var bob = { 
    firstName: "Bob", 
    lastName: "Jones", 
    phoneNumber: "(650) 777-7777", 
    email: "[email protected]" 
}; 

var mary = { 
    firstName: "Mary", 
    lastName: "Johnson", 
    phoneNumber: "(650) 888-8888", 
    email: "[email protected]" 
}; 

// printPerson added here 
function printPerson(person){ 
    console.log(person.firstName + " " + person.lastName); 

} 

printPerson(bob); 
printPerson(mary); 

我的問題是,如何通過使用this關鍵字來改善上述代碼。現在,我已經看到OOP(或者我錯了?)。

extra:不需要構造函數,或者像new關鍵字那樣更復雜的東西。

+0

「_Need no constructor or something more complex like new keyword._」。除非你要實現一個'Object.prototype'方法或使用'Object.create'(它是「複雜的」),否則沒有辦法。 –

回答

0

printPerson方法的問題是,當你需要「多態」;即要打印的對象,但你不想知道什麼樣的對象是的:假設

function newPerson(firstName, lastName) { 
    return { firstName: firstName, 
      lastName: lastName }; 
} 

function newPet(name, kind) { 
    return { name: name, 
      kind: kind }; 
} 

function printPerson(person) { 
    console.log(person.firstName + " " + person.lastName); 
} 

function printPet(pet) { 
    console.log(pet.name + " (a nice " + pet.kind + ")"); 
} 

var p1 = newPerson("Andrea", "Griffini"); 
var p2 = newPet("Tobi", "cat"); 

printPerson(p1); 
printPet(p2); 

但問題是...假設你給一個對象x,你需要打印它,但你不知道它是一個人還是一個寵物...你怎麼做? 解決方案1與if/then

if (x.firstName) { 
    printPerson(x); 
} else { 
    printPet(x); 
} 

檢查,但是因爲如果以後添加其他類型的你需要修復該對象的這很煩人。

的OOP的解決辦法是改變代碼稍

function Person(firstName, lastName) { 
    this.firstName = firstName; 
    this.lastName = lastName; 
    this.print = function() { 
     console.log(this.firstName + " " + this.lastName); 
    }; 
} 

function Pet(name, kind) { 
    this.name = name; 
    this.kind = kind; 
    this.print = function() { 
     console.log(this.name + " (a nice " + this.kind + ")"); 
    }; 
} 

現在使用變得

var p1 = new Person("Andrea", "Griffini"); 
var p2 = new Pet("Tobi", "cat"); 

p1.print(); 
p2.print(); 

和一般x問題就是x.print()

基本上這個想法是將數據(例如firstNamelastName)和代碼(例如print的實現)保存在一起用於每種類型的對象。 只需實施構造函數即可添加新的對象類型,而無需更改其他代碼,這些代碼將「神奇地」調用print的正確版本。

1
function Person(firstName, lastName, phoneNumber, eMail) { 
    var that = this; 
    that.firstName = firstName; 
    that.lastName = lastName; 
    that.phoneNumber = phoneNumber; 
    that.eMail = eMail; 
    return { 
     printPerson: function() { 
      console.log(that.firstName + " " + that.lastName); 
     } 
    } 
}; 

var person1 = Person("Bruce", "Wayne", "1234", "[email protected]"); 
person1.printPerson(); 

var person2 = Person("Kent", "Clark", "4321", "[email protected]"); 
person2.printPerson(); 
+0

來自提問者的奇怪要求,但是:「_不需要構造函數或更復雜的內容,比如new keyword_」。儘管這可能是最理智的方法。此外,任何只返回'printPerson'方法的原因? –

+1

@ Qantas94Heavy它僅用於演示。而且,他只有在問題中才有'printPerson':) – thefourtheye