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

时间:2015-02-27 00:46:53

标签: javascript

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

为什么没有显示

3 个答案:

答案 0 :(得分:1)

由于this.age未定义,因此未显示。你想要age

答案 1 :(得分:0)

由于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

答案 2 :(得分:0)

你想要这个:

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"应该