简体   繁体   English

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

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

My code is as shown below:我的代码如下所示:

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

When I run this code, it gives me the following error:当我运行此代码时,它给了我以下错误:

TypeError: person.getName is not a function

use console.log instead of print and don't forget to attach functions to objects using this.使用console.log而不是print并且不要忘记使用this.将函数附加到对象this. notation符号

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

try replacing it with this.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())

ALternatively you can add getName to it's prototype或者,您可以将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())

You need to construct by using this so that your instance can get it's own params:您需要使用this来构造,以便您的实例可以获得它自己的参数:

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

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

first of all, for function constructors you use this :首先,对于函数构造函数,你使用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'

Second, get used to using ES6 classes:其次,习惯使用 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
  }
}

I think your lacking basics, do personal research before asking on StackOverflow.我认为您缺乏基础知识,请在询问 StackOverflow 之前进行个人研究。

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

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