My Octopress Blog

A blogging framework for hackers.

Constructor 和 Prototype的关系

| Comments

constructor 和 prototype的关系

  • constructor标明对象的类型
1
2
3
    function Test(){}
    var test = new Test();
    console.log(test.constructor); //function Test(){}
  • prototype(原型链)只有对象才有的属性,而不是通过new形成的实例
1
2
3
4
5
    function Test(){}
    Test.prototype.print = function(){console.log("Test print");};
    var test = new Test();
    test.print(); //Test print
    console.log(Test.prototype); //Test {print: function}
  • prototype有不可枚举的constructor属性,这个属性会默认指向当前的function. 对象的constructor就是继承该值.如果对prototype重新赋值,实例会丢失当前的constructor,从prototype获得一个新的constructor.
1
2
3
4
5
6
7
8
9
10
11
12
    function Test(){}
    var test1 = new Test();

    Test.prototype = {
        print: function(){console.log("Test's print");}
    }
    var test2 = new Test();

    console.log(test1.constructor); //function Test()
    console.log(test2.constructor); //function Object()
    console.log(test2.print()); //Test's print
    console.log(test1.print()); //undefined
  • 解决上面的问题,但是之前定义的实例的prototype仍是指向原prototype,不会有后来定义的方法。
1
2
3
4
5
6
7
8
9
10
11
12
13
    function Test(){}
        var test1 = new Test();

    Test.prototype = {
        constructor: Test,
        print: function(){console.log("Test's print");}
    }
    var test2 = new Test();

    console.log(test1.constructor); //function Test()
    console.log(test2.constructor); //function Test()
    console.log(test2.print()); //Test's print
    console.log(test1.print()); //undefined

Comments