2015-02-27 3 views
0
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 

Почему он не получает отображаетсяИспользование частных пользователей и методы в JavaScript

+0

'this.getAge()' –

+2

Что вы называете «частным членом», являются простыми * локальными переменными *. Вы не сможете получить к ним доступ, используя 'this'. Читайте http://stackoverflow.com/q/13418669/1048572 – Bergi

ответ

1

Это не отображается, потому что this.age не определено. Вы хотите age.

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

Обратите внимание, что оба «СеЬАд» и «displayAge» необходимо прикрепить к this, но ваша личная переменная «возраст» должна быть не be.

Смежные вопросы