推荐关注
› Meteor
› JSLint - a JavaScript code quality tool
› jsFiddle
› D3.js
› WebStorm
推荐书目
› JavaScript 权威指南第 5 版
› Closure: The Definitive Guide
lbfeng

js 原型 constructor 的困惑

  •  
  •   lbfeng · Jun 24, 2019 · 4130 views
    This topic created in 2688 days ago, the information mentioned may be changed or developed.
    function Foo(name) {
    	this.name = name;
    }
    
    Foo.prototype.myName = function() {
    	return this.name;
    };
    
    function Bar(name,label) {
    	Foo.call( this, name );
    	this.label = label;
    }
    
    console.log(Bar.prototype.constructor);
    
    Bar.prototype = Object.create( Foo.prototype );
    
    console.log(Bar.prototype.constructor);
    
    Bar.prototype.myLabel = function() {
    	return this.label;
    };
    
    var a = new Bar( "a", "obj a" );
    
    a.myName(); // "a"
    a.myLabel(); // "obj a"
    console.log(a.constructor);"
    

    第 1 次输出 Bar.prototype 的 constructor 指向 Bar 完全可以理解。 function Bar(name,label){Foo.call(this,name);this.label=label;}

    第 2, 3 次输出 Bar.prototype 的 constructor 指向 Foo 也完全可以理解。 function Foo(name){this.name=name;} function Foo(name){this.name=name;}

    如果 new Bar 有用到 Bar.prototype.constructor 的话 label 是怎么放入 a 的? 要是没用到的话 constructor 有什么意义?

    画了个图帮助理解 i.imgur。com/k5LMrEV.jpg

    6 replies  •  2019-07-19 05:42:29 +08:00
    lbfeng
    lbfeng
    OP
    Jun 24, 2019
    1
    imgur。com/a/dQZ821s
    connection
    connection
    Jun 25, 2019
    2
    Bar.prototype = Object.create( Foo.prototype );

    访问 a 实例的时候访问 constructor 实际上在访问 Foo.prototype 上的 constructor 了吧
    lbfeng
    lbfeng
    OP
    Jun 25, 2019
    3
    @connection 是的,第二个输出证明这点。
    azh7138m
    azh7138m
    Jul 9, 2019
    4
    > label 是怎么放入 a

    不是你自己写的吗?
    function Bar(name,label) {
    Foo.call( this, name );
    this.label = label;
    }

    this.label = label;
    lbfeng
    lbfeng
    OP
    Jul 10, 2019
    5
    @azh7138m 第 4 次输出没写全。a.constructor 是 Foo 而不是 Bar. 这才是我要问的问题。是 Bar 的话我就不用问了。。。
    lbfeng
    lbfeng
    OP
    Jul 19, 2019
    6
    我自己终结吧。var a = new Bar(…)。这个和 new 的过程有关。

    1. Create a new empty object.
    2. Assign the “ this ” value of the constructor function to the new empty object (so this points to the new object).
    3. Execute the code inside the constructor function (adds properties to the new object).
    4. Return the new object if constructor function doesn ’ t have a explicit return statement.

    所以整个创建过程和 prototype.constructor 没啥关系。
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   5616 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 37ms · UTC 03:03 · PVG 11:03 · LAX 19:03 · JFK 22:03
    ♥ Do have faith in what you're doing.