实例的__proto__与javascript中构造函数的原型之间的关系

时间:2012-01-31 14:58:16

标签: javascript prototype

我编写代码来为我弄清楚实例的__proto__与javascript中构造函数的原型之间的关系:

// Constructor
var Guy = function( name ) {
       this.name = name;
};

// Prototype
var chinese = {
        region: "china",
        myNameIs: function() {
            return this.name;
        }
};

Guy.prototype = chinese;

var he = new Guy( "Wang" );
var me = new Guy( "Do" );

我得到了false,因为我测试了我.__ proto__是否等于中文:

console.log( "__proto__ of me is chinese? " + chinese == me.__proto__ ); // logs false

他们为什么不是一回事?

1 个答案:

答案 0 :(得分:3)

因为+的优先级高于==,所以你真的在做...

( "__proto__ of me is chinese? " + chinese ) == me.__proto__

你需要做的是......

"__proto__ of me is chinese? " + ( chinese == me.__proto__ )

或在,调用中使用console来传递单独的参数......

"__proto__ of me is chinese? ", chinese == me.__proto__