javascript函数无法访问该对象的私有成员

时间:2018-03-04 06:56:17

标签: javascript

我的代码如下所示:

function myClickHandler() {
    remove = true;
}
arr.forEach(value => value.addEventListener("click", myClickHandler));
if (remove) {
    arr.forEach(value => value.removeEventListener("click", myClickHandler);
}

当我运行此代码时,它会给我以下错误:

function Person (firstName,lastName,age){
    var firstName = firstName;
    var lastName = lastName;
    var age = age;

    function getName(){
        return firstName+ " " + lastName;
    }
}



var person = new Person("m","t",297)

print(person.getName())

3 个答案:

答案 0 :(得分:2)

使用console.log代替print,不要忘记使用this.符号将对象附加到对象

function Person (firstName,lastName,age){
    var firstName = firstName;
    var lastName = lastName;
    var age = age;

    this.getName = function(){
        return firstName+ " " + lastName;
    }
}

 

var person = new Person("m","t",297)

console.log(person.getName())

答案 1 :(得分:1)

尝试将其替换为this.getName

function Person(firstName, lastName, age) {
  var firstName = firstName;
  var lastName = lastName;
  var age = age;
  this.getName = function() {
    return firstName + " " + lastName;
  }
}



var person = new Person("m", "t", 297)

console.log(person.getName())

您也可以将getName添加到prototype

function Person(firstName, lastName, age) {
  this.firstName = firstName;
  this.lastName = lastName;
  this.age = age;

}
Person.prototype.getName = function() {
  return this.firstName + " " + this.lastName;
}
var person = new Person("m", "t", 297)
console.log(person.getName())

答案 2 :(得分:1)

您需要使用this进行构建,以便您的实例可以获得它自己的参数:

function Person (firstName,lastName,age){
    this.firstName = firstName;
    this.lastName = lastName;
    this.age = age;

    this.getName = function() {
        return this.firstName+ " " + this.lastName;
    }
}