palmers
V2EX  ›  Node.js

有以下代码不明白,请大家帮忙解惑,谢谢大家啦!

  •  
  •   palmers · May 25, 2016 · 3781 views
    This topic created in 3703 days ago, the information mentioned may be changed or developed.
     function Cat(){} 
     function F() {}
     F.prototype = cat ;
    
    var f = new F()
    

    查看 f 的 constructor 发现自动就修正为 Cat 了? 为什么呢? 是因为 new 关键字的作用吗?

    谢谢大家啦!

    Supplement 1  ·  May 26, 2016

    不好意思,少一行代码:

    var cat = new Cat() ;
    
    8 replies    2016-05-26 11:13:01 +08:00
    jarlyyn
        1
    jarlyyn  
       May 25, 2016   ❤️ 1
    ChiangDi
        2
    ChiangDi  
       May 25, 2016
    没有吧,运行之后 f.constructor.name 是 Function, 因为 Cat.constructor 是 Function
    SuperMild
        3
    SuperMild  
       May 25, 2016 via iPad
    与其说修正,不如说是被污染(覆盖)了。 constructor 在 prototype 里面。
    F.prototype.constructor === f.constructor
    daysv
        4
    daysv  
       May 25, 2016
    这代码有问题吧? 小写 cat? 另外建议问这类问题之前多看看书
    Sunyanzi
        5
    Sunyanzi  
       May 25, 2016
    只有我觉得这毫无悬念的就是一个简单的原型链继承吗 ...

    F.prototype 是小写的 cat ... 我估计 LZ 把 cat = new Cat 这行当作没用的东西给删了 ...
    magicdawn
        6
    magicdawn  
       May 25, 2016
    f.hasOwnProperty('constructor') // false
    f.constructor === cat.constructor // true
    palmers
        7
    palmers  
    OP
       May 26, 2016
    @daysv 不好意思 少一行代码
    ```javascript

    var cat = new Cat() ;
    ```
    jerray
        8
    jerray  
       May 26, 2016
    不就是继承么

    建议参考 https://www.h5jun.com/post/inherits.html
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   3132 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 41ms · UTC 12:52 · PVG 20:52 · LAX 05:52 · JFK 08:52
    ♥ Do have faith in what you're doing.