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

在构造函数内外为 prototype 属性赋值的区别

  •  
  •   coolzjy · 2015-04-18 20:43:08 +08:00 · 2723 次点击
    这是一个创建于 3298 天前的主题,其中的信息可能已经有所发展或是发生改变。

    function Person(){
        Person.prototype.talk=function(){alert("saying")};
    }
    
    function Men(){
    }
    
    Men.prototype = new Person();
    
    var men = new Men();
    men.talk();
    

    可以执行成功,但

    function Person(){
        Person.prototype.talk=function(){alert("saying")};
    }
    
    function Men(){
        Men.prototype = new Person();
    }   
    
    var men = new Men();
    men.talk();
    

    报错。请问在构造函数内部和外部为 prototype 赋值有何区别

    4 条回复    2015-04-19 11:36:20 +08:00
    iyangyuan
        1
    iyangyuan  
       2015-04-18 21:14:11 +08:00 via iPhone   ❤️ 1
    因为第二个在new的时候,你还没有指定原型。

    new相当于创建一个新对象,然后把这个新对象的原型指向函数(类)的prototype对象,第二个在构造方法里才指定原型,此时新对象的创建已经完成,它早已指向别处,所以报错。

    在第二个例子中,如果再new一次,应该就不会报错了。
    bombless
        2
    bombless  
       2015-04-18 23:15:21 +08:00
    function Men(){
    function ret() {}
    ret.prototype = new Person();
    ret = new ret;
    Men = ret;
    return ret
    }
    作弊可以吗,哈哈哈
    xavierchow
        3
    xavierchow  
       2015-04-18 23:43:49 +08:00
    请看https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/new
    ```
    When the code new foo(...) is executed, the following things happen:

    1. A new object is created, inheriting from foo.prototype.
    2.The constructor function foo is called with the specified arguments and this bound to the newly created object. new foo is equivalent to new foo(), i.e. if no argument list is specified, foo is called without arguments.
    3.The object returned by the constructor function becomes the result of the whole new expression. If the constructor function doesn't explicitly return an object, the object created in step 1 is used instead. (Normally constructors don't return a value, but they can choose to do so if they want to override the normal object creation process.)
    ```
    第一步的时候,Men的prototype还不是Person对象,第二步才是执行constructor,而在你的代码中这时才改Men的prototype, 晚了。
    xavierchow
        4
    xavierchow  
       2015-04-19 11:36:20 +08:00
    补充一点,对象初始化之后prototype是不可以改变,但是可以修改prototype的属性。
    所以new之后再assign prototype是不行的,但是(new Person()).talk()是OK的。
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   1376 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 26ms · UTC 17:21 · PVG 01:21 · LAX 10:21 · JFK 13:21
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.