使用javascript调用this或其他函数

calling this of other function using javascript

本文关键字:其他 函数 this javascript 调用 使用      更新时间:2023-09-26

如何调用下面的函数,我的预期输出是"嗨,约翰,我的名字是詹姆斯"

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

名称在上面的代码中没有定义

使用this.name

function Person(name){
  this.name = name;
}
Person.prototype.greet = function(otherName){
  return "Hi " + otherName + ", my name is " + this.name;
}
var p = new Person("Foo");
console.log(p.greet("Bar"));   // "Hi Bar, my name is Foo"

访问附加在这个对象上的属性,嗯…你必须调用this.

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