首页 > 构造函数为什么不生效?

构造函数为什么不生效?

function Person(name,age,job) {   
    this.name=name;
// 要用构造函数起名时候要首字母大写  
    this.age=age;
    this.job=job;
    this.sayName=function () {
        alert(this.name);
    };
}

var person3=new Object("Nicholas",29,"Software Engineer");
var person4=new Object('Greg',27,"Doctor");

console.log(person3.name); // undefined

console.log(person3.constructor==Person); //false
console.log(person4.constructor==Person); //false
console.log(person3 instanceof Object); //true
console.log(person3 instanceof Person); //false
console.log(person4 instanceof Object); //true
console.log(person4 instanceof Person); //false

你 new Object() 干哈? 你new Person()呀。function Object(){}是有这么个东东,但是发明者在它里面是没有 定义 this.name 所以 当然是undefined了。你的this.name 是写在Person里的呀!


....................


你的构造函数名字叫做Person
但是你自己用的时候却是var person3=new Object("Nicholas",29,"Software Engineer");
那最后console.log(person3.name);这里肯定是undefined了
你要访问person3.name,那你肯定需要new Person啊,不然你怎么找的到~


new Person();

【热门文章】
【热门文章】