Javascript instanceof并不像我期望的那样工作

时间:2015-09-28 07:46:36

标签: javascript inheritance

我正在学习javascript并写下以下代码。

var Parent = (function() { return function() {};})();
var Child = (
    function() { 
        return function(p) {
            var F = new Function();
            F.prototype = p.prototype;
            Child.prototype = new F();
        };
    })();

var p = new Parent();
var c = new Child(Parent);
console.log(p instanceof Parent);
console.log(c instanceof Parent);

c instanceof Parent返回false,这与我的期望不符!!

然后我将代码更改为:

var Parent = (function() { return function() {};})();
var Child = (function() { return function() {};})();
var F = new Function();
F.prototype = Parent.prototype;
Child.prototype = new F();
var p = new Parent();
var c = new Child();
console.log(p instanceof Parent);
console.log(c instanceof Parent);

这次c instanceof Parent返回true。 谁能回答原因?

0 个答案:

没有答案