JavaScript谜题我可以'我想不通

JavaScript Puzzle I can't figure out

本文关键字:想不通 我可以 JavaScript      更新时间:2023-09-26

这是一个代码战的卡塔,我似乎无法理解。我以前从未使用过JavaScript。

我知道答案可能很简单,但即使经过几个小时的搜索,我似乎也不明白他们在寻找什么。我知道greet函数中的name没有定义,但当我定义它时,它会说它不是它要查找的值。

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

请帮忙,如能解释,我们将不胜感激。

我真的不明白你在寻找什么,但希望这能带来一些启示:(在你的控制台上试试)

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');

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"));

如果你点击这个JSFiddle,你可以看到它确实在工作。两者的区别只是在greet()函数中将"name"更改为"this.name"。您将向每个Person对象附加一个新函数,但它不会按照定义的方式自动在该函数中查找对象上的名称变量。

我不明白你的问题,但我会尝试解释它是如何工作的:

// 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链接:http://jsfiddle.net/QqnL5/