JavaScript拼图我想不出来

时间:2013-11-20 04:24:44

标签: javascript puzzle

这是代码大战的kata,我似乎无法弄明白。我之前从未使用过JavaScript。

我知道答案可能很简单,但即使经过数小时的搜索,我也似乎无法弄清楚他们在寻找什么。我知道name函数中的greet未定义,但是当我定义它时,它表示它不是它正在寻找的值。

function Person(name){
  this.name = name;
}

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

请帮助,我们将非常感谢您的解释。

3 个答案:

答案 0 :(得分:3)

不要真正理解你在寻找什么,但希望这会有所启发:(试试你的控制台)

function Person(name){
  this.name = name;
}

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

var p = new Person('jack');

p.greet('sparrow');

答案 1 :(得分:1)

Tyagi向您解释了如何调用它但未显示代码的实际问题是:

这是我(非常相似)的例子:

function Person(name) {
  this.name = name;
}

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

var john = new Person("John");

$("#result").text(john.greet("Mike"));

如果您click through to this JSFiddle,那么您可以看到它确实有效。两者之间的区别仅仅是在greet()函数中将“name”更改为“this.name”。您将新函数附加到每个Person对象,但它不会按照定义的方式自动在该函数中的对象上查找名称变量。

答案 2 :(得分:1)

我没有得到您的问题,但我会尝试解释它是如何运作的:

// define a function (or class) called 'Person'
function Person(name){
  // add data members 'name' to 'this' pointer which points to current context
    this.name = name;
}

// define a method in 'Person' class 
Person.prototype.greet = function(otherName){
    //'othername' is an argument which you passed while calling 'greet' method
    //'name' is an data memeber which you declared while creating 'Person' class
    // will return value when you call this method
    return "Hi " + otherName + ", my name is " + this.name;
}

// create a class object
var person = new Person('Mohit');
// call its 'greet' method
// will show an alert 'Hi Bekk, my name is Mohit'
alert(person.greet('Bekk'));

JSFiddle Link: http://jsfiddle.net/QqnL5/