首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 网站开发 > JavaScript >

js中constructor属性的有关问题

2013-03-10 
js中constructor属性的问题。先看第一段代码:function Person(name) {this.name name}Person.prototype

js中constructor属性的问题。
先看第一段代码:
function Person(name) {
this.name = name;
};
Person.prototype.getName = function() {
return this.name;
};
var p = new Person("ZhangSan");

console.log(p.constructor === Person); // true
console.log(Person.prototype.constructor === Person); // true
其实p对象生成时并没有constructor属性,当访问constructor属性时,会向原型链上查找constructor属性。
第二段代码:
<html>
<body>
<script type="text/javascript">
function Users(){
}
Users.prototype=5;
var u=new Users();
console.log(u.constructor);
</script>
</body>
</html>
输出的是Object();
可是u对象没有constructor属性,当访问u.constructor时找不到,就会向Users.prototype指向的对象(prototype对象中有个constructor属性)中查找,但是现在Users.prototype=5;所以,理论上console.log(u.constructor);应该输出Number()类型的。这是怎么回事?教程上说constructor属性指向构造函数的,不知道内部怎么实现的,请分析下。

热点排行