Codewars构造函数

时间:2016-06-11 17:00:10

标签: javascript constructor

我遇到了来自codewars.com的Javascript挑战。它看起来是一个构造函数(?)函数,我以为我知道但是唉,没有。 我在MDN和其他地方寻找了一些例子。 我宁愿知道错误的观点而不是直接的答案,看看我是否能算出自己。 挑战:

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

2 个答案:

答案 0 :(得分:0)

您尝试过的代码非常错误,但不是给您代码(因为您正在尝试学习它),我会给您一些指示。

new声明后,function关键字无法使用。它用于创建方法new Person()

的新实例

greet方法中,未定义name。您需要使用适当的范围来获取名称。

greet.fullName()也没有定义,你想要的是访问fullName变量的方法。

答案 1 :(得分:-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.




编辑:在评论中放置解释