在 javascript 中使用私有成员和方法

Using private members and methods in javascript

本文关键字:成员 方法 javascript      更新时间:2024-06-06
var test = function(id, company){
    //public members
    this.id = id;
    this.company = company;
    //private member
    var age = 24;
    //private method
    var getAge = function(){
       return this.age;
    };
    //public method
    this.displayAge = function(){
       console.log(getAge());
    }
}
//invoking 
var t = new test(1, 'XYZ Corp');
t.displayAge(); //undefined

为什么它没有显示

它没有显示,因为它未定义this.age。 你想要age.

因为 js 中变量的作用域

变量在函数

内部可见,在函数外部可见

var a = "foo"
function fooBar () {
  var b = "bar"
  console.log(a) // foo
  console.log(b) // bar
}
console.log(a) // foo
console.log(b) // undefined

你想要这个:

var test = function(id, company){
    //public members
    this.id = id;
    this.company = company;
    //private member
    var age = 24;
    //private method
    this.getAge = function(){
       return age;
    };
    //public method
    this.displayAge = function(){
       console.log(this.getAge());
    }
}
//invoking 
var t = new test(1, 'XYZ Corp');
t.displayAge(); //undefined

请注意,"getAge"和"displayAge"都需要附加到this但您的私有变量"age">不应该附加到。