javascript - 构造函数为什么不生效?
本文介绍了javascript - 构造函数为什么不生效?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
问 题
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里的呀!
这篇关于javascript - 构造函数为什么不生效?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文