繁体   English   中英

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

[英]javascript function is not able to access private member of the object

我的代码如下所示:

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())

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

TypeError: person.getName is not a function

使用console.log而不是print并且不要忘记使用this.将函数附加到对象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())

尝试用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())

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

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

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

首先,对于函数构造函数,你使用this

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

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

其次,习惯使用 ES6 类:

class Person {
  constructor(name, last, age) {
    this.name = name;
    this.last = last;
    this.age = age;
  };

  getName() {
    return `${this.name} ${this.last}` //using ES6 string template literal
  }
}

我认为您缺乏基础知识,请在询问 StackOverflow 之前进行个人研究。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM