V2EX = way to explore
V2EX 是一个关于分享和探索的地方
Sign Up Now
For Existing Member  Sign In
推荐关注
Meteor
JSLint - a JavaScript code quality tool
jsFiddle
D3.js
WebStorm
推荐书目
JavaScript 权威指南第 5 版
Closure: The Definitive Guide
guotie

请教一个 javascript extend 问题

  •  
  •   guotie · Aug 26, 2014 · 3534 views
    This topic created in 4265 days ago, the information mentioned may be changed or developed.
    代码如下:

    function noop() {
    this.name = 'this.name'
    }
    function _extend(source, obj) {
    for (var prop in source) {
    if(!obj.prototype[prop]) {
    obj.prototype[prop] = source[prop]
    }
    }
    return obj
    }

    noop.prototype["name"] = 'noop'

    _extend({"title":"sometitle"}, noop)

    var n = new noop()
    console.log( noop.name, noop.title, noop.prototype.name, noop.prototype.title, noop.prototype)
    console.log( n.name, n.title)

    输出结果如下:
    noop undefined noop sometitle { name: 'noop', title: 'sometitle' }
    'name' 'sometitle'

    问题是:
    为什么noop.name可以取到值,而noop.title无法取到值,而name和title都在noop.prototype中
    4 replies    2014-09-01 10:09:53 +08:00
    guotie
        1
    guotie  
    OP
       Aug 26, 2014
    上面的function noop的定义是这样的:
    function noop (){}

    jsbin在线调试地址:
    http://jsbin.com/jihijinurutu/1/edit?js,console
    larvata
        2
    larvata  
       Aug 26, 2014   ❤️ 1
    你取到的 noop.name不是noop.prototype里定义的name
    而是function noop() 的名字
    guotie
        3
    guotie  
    OP
       Aug 26, 2014
    原来如此!

    多谢!
    rekey
        4
    rekey  
       Sep 1, 2014
    noop.title 取不到值是因为

    noop.prototype === Function
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   841 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 28ms · UTC 21:13 · PVG 05:13 · LAX 14:13 · JFK 17:13
    ♥ Do have faith in what you're doing.