2016-06-11 160 views
-2

我被困在Codewars.com的Javascript挑戰中。它看起來是一個構造函數(?)函數,我認爲我知道,但唉,不。 我在MDN和其他地方尋找例子。 我寧願知道錯誤的觀點而不是直截了當的答案,看看我能否認出我自己。 挑戰:Codewars構造函數

function new Person(name){ 
    this.name = name; 
    return name; 
} 
Person.prototype.greet = function(otherName){ 
    return "Hi " + otherName + ", my name is " + name; 
}; 

通過做一些研究,我想也許增加了構造的兩個名字會做,但再次得到一個「意外的標記新」的錯誤。我嘗試:

function new Person(name, otherName){ 
 
    this.name = name; 
 
    this.otherName = otherName; 
 
    return name + " " + otherName; 
 
} 
 

 
Person.prototype.greet = function(otherName){ 
 
    return "Hi " + otherName + ", my name is " + name; 
 
}; 
 
var fullName = new Person("Fred", "Jones"); 
 
greet.fullName();

耐心,我的無知,是極大的讚賞。 謝謝, pychap

+0

請仔細閱讀[問]。這裏沒有一個適當的問題陳述,也沒有一個具體的問題 – charlietfl

+0

只需開始在* javascript工廠模式*上搜索,嘗試一下,然後回來一個更加一致的例子。那麼我們很樂意爲您提供幫助! – pietro909

回答

0

你試過的代碼是相當錯誤的,而不是給你的代碼(因爲你正在嘗試學習它),我會給你一些指示。

new關鍵字在function聲明後無法使用。它用於創建方法的新實例new Person()

greet方法中,未定義name。您將需要使用適當的範圍來獲取名稱。

greet.fullName()也沒有定義,你想要的是訪問fullName變量的方法。

+2

另外contstructor函數通常不應該返回任何東西。 – Barmar

-1

function Person(firstName, lastName){ //declaration of function named person taking 2 arguments 
 
    this.firstName = firstName; //creating variable holding firstName 
 
    this.lastName = lastName; //same as above but for lastName 
 
//removed return as constructor functions shouldnt return anything, you call this function with 'new' which already creats content of your object 
 
} 
 

 
Person.prototype.greet = function(){ //this is another declaration but for greet function. You can think about it like a function you can call but only for variables holding Person object 
 
    return "Hi " + this.firstName + " " + this.lastName; //use 'this' to tell your program to work on object that calls this function (greet()) 
 
}; 
 

 
var fullName = new Person("Fred", "Jones"); //this is point of your program - in variable fullName it creates an object using your function Person. Since now all methods that has Person you can call on fullName variable. 
 
console.log(fullName.greet()); // here I use console.log to print resutl of fullName.greet() call. I defined fullName and I have put object into it created with Person function. Now I place fullName first, then calling one of methods it owns - greet(). Result is sentence defined in greet declaration.

編輯:在註釋中放置解釋

+1

Downvote因爲你所做的只是提供代碼來解決它,而沒有任何解釋爲什麼這會修復它 –

+0

好的,那麼我會解釋發生了什麼。正在編輯。 –

+1

你爲什麼從'Person()'函數中刪除'return'語句?我知道答案,但你需要在答案中解釋它。 – Barmar