先看第一段代码:
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属性指向构造函数的,不知道内部怎么实现的,请分析下。javascriptjsconstructor

解决方案 »

  1.   

    Users.prototype=5;
    上面这句会使constructor指向Object,一般使用下面种形式后
    Users.prototype = {
        getName:function(){
    },setName:function(){
    }
    }还要再加一句
    Users.prototype.constructor = Users;
    不然实例访问constructor的时候就得不到想要的结果。
      

  2.   

    Person.prototype.getName=xxx;
    Users.prototype=5;
    你没注意到这两个根本不是一回事么 一个原型prototype中的属性 一个直接覆盖原型
      

  3.   

    你觉得是一回事吗?
    Person.prototype.getName=xxx;
    这个是给原型添加一个属性,属性值为xxxx
    Users.prototype=5;
    这个是重新指定原型。
      

  4.   

    我做这样的测试:
    改变a.prototype之后,用 Object.getPrototypeOf() 检查test对象的原型。前四个使用new 运算符的,原型都和new 之后的类型对应。
    但是后面四个有所不同:
    等于0 和等于'str'之后,test的原型都是Object对象。
    等于function和/e/之后,test的原型分别是function test本身和/e/本身。
    原型不同,构造函数自然也不同。
    我这只是测试出来的结果,具体是个怎么机制,还是得等别人回答。function a () {}
    // a.prototype = new Number();  
    // a.prototype = new String();     
    // a.prototype = new Function();
    // a.prototype = new RegExp();  
    // a.prototype = 0; 
    // a.prototype = 'str';
    // a.prototype = function test() {};
    // a.prototype = /e/;
    var test = new a();
    console.log(Object.getPrototypeOf(test));
      

  5.   

    In the specification of ECMAScript Language Specification (Edition 3):13.2.2 [[Construct]]
    When the [[Construct]] property for a Function object F is called, the following steps are taken:
    1. Create a new native ECMAScript object.
    2. Set the [[Class]] property of Result(1) to "Object".
    3. Get the value of the prototype property of the F.
    4. If Result(3) is an object, set the [[Prototype]] property of Result(1) to Result(3).
    5. If Result(3) is not an object, set the [[Prototype]] property of Result(1) to the original Object prototype object as described in section 15.2.3.1.
    6. Invoke the [[Call]] property of F, providing Result(1) as the this value and providing the argument list passed into [[Construct]] as the argument values.
    7. If Type(Result(6)) is Object then return Result(6).Step 5 gives the answer of your question.
    因为 Users.prototype 是 5, 不是 Object, 所以 u 的内涵原型链[[Prototype]]是 Object, 不是 Users.prototype.
    u.constructor --> u.[[Prototype]].constructor --> Object.constructor --> Object()