无法通过javascript中的特权方法访问私有方法

时间:2014-10-23 17:53:18

标签: javascript oop inheritance

错误:在尝试打印年龄函数时控制台中出现未定义错误

var Person = function( myName, myProfession, myage ){
        this.name = myName;  // Public Variable 
        this.profession = myProfession;
        var age = myage;  // Private Variable 
        this.myAge = function(){  // Privilaged Method
            return this.age;
        };
        };
      var syed = new Person('syed azam','developer',20);
      console.log(syed + "works fine");
      console.log(syed.myAge());
<script src="https://getfirebug.com/firebug-lite-debug.js"></script>

1 个答案:

答案 0 :(得分:2)

什么是this.age?您没有正确封装它:

this.myAge = function(){
    return myage;
};

请注意,您不必使用var age = myage;。的 DEMO.