2016-06-11 164 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