开发者

Why is variable in prototypal constructor undefined when accessed as a property?

开发者 https://www.devze.com 2023-03-13 15:47 出处:网络
Why is myPerson.age undefined? function Person() { var age = 28; } var myPerson = new Person(); console.log(myPerson.age);

Why is myPerson.age undefined?

function Person() {
  var age = 28;
}

var myPerson = new Person();

console.log(myPerson.age);

I have clearly set what the varaible is in the Person function construtor which 开发者_运维问答should be pointed to by the .prototype of myPerson, no?


Try this:

function Person(){

    this.age = 28;

}


$(document).ready(function(){


  var myPerson = new Person();

  console.log(myPerson.age);


});
0

精彩评论

暂无评论...
验证码 换一张
取 消