V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐关注
Meteor
JSLint - a JavaScript code quality tool
jsFiddle
D3.js
WebStorm
推荐书目
JavaScript 权威指南第 5 版
Closure: The Definitive Guide
lbfeng
V2EX  ›  JavaScript

js 原型 constructor 的困惑

  •  
  •   lbfeng · 2019-06-24 23:17:27 +08:00 · 3003 次点击
    这是一个创建于 1759 天前的主题,其中的信息可能已经有所发展或是发生改变。
    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 条回复    2019-07-19 05:42:29 +08:00
    lbfeng
        1
    lbfeng  
    OP
       2019-06-24 23:24:56 +08:00
    imgur。com/a/dQZ821s
    connection
        2
    connection  
       2019-06-25 00:24:59 +08:00
    Bar.prototype = Object.create( Foo.prototype );

    访问 a 实例的时候访问 constructor 实际上在访问 Foo.prototype 上的 constructor 了吧
    lbfeng
        3
    lbfeng  
    OP
       2019-06-25 04:42:41 +08:00
    @connection 是的,第二个输出证明这点。
    azh7138m
        4
    azh7138m  
       2019-07-09 15:46:35 +08:00
    > label 是怎么放入 a

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

    this.label = label;
    lbfeng
        5
    lbfeng  
    OP
       2019-07-10 00:32:24 +08:00
    @azh7138m 第 4 次输出没写全。a.constructor 是 Foo 而不是 Bar. 这才是我要问的问题。是 Bar 的话我就不用问了。。。
    lbfeng
        6
    lbfeng  
    OP
       2019-07-19 05:42:29 +08:00
    我自己终结吧。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 没啥关系。
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   5975 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 29ms · UTC 02:31 · PVG 10:31 · LAX 19:31 · JFK 22:31
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.