2017-07-19 60 views
0

我在阅读javascript-spessore时遇到了问题; 的问题来自参数与原型之间的关系, 以下是代码片段,我把它放在https://jsfiddle.net/abramhum/wf0vom9x/4/关于javascript的原型和参数

function Class() { 
    return { 
    create: function() { 
     var instance = Object.create(this.prototype); 
     Object.defineProperty(instance, 'constructor', { 
     value: this 
     }); 
     if (instance.initialize) { 
     instance.initialize.apply(instance, arguments); 
     } 
     return instance; 
    }, 
    defineMethod: function(name, body) { 
     this.prototype[name] = body; 
     return this; 
    }, 
    prototype: {} 
    }; 
} 

var QuadTree = Class(); 

QuadTree.defineMethod(
    'initialize', 
    function(nw, ne, se, sw) { 
    this.nw = nw; 
    this.ne = ne; 
    this.se = se; 
    this.sw = sw; 
    } 
).defineMethod(
    'population', 
    function() { 
    return this.nw.population() + this.ne.population() + 
     this.se.population() + this.sw.population(); 
    } 
); 

var BasicObjectClass = { 
    prototype: {} 
} 

function Class(superclass) { 
    return { 
    create: function() { 
     var instance = Object.create(this.prototype); 
     Object.defineProperty(instance, 'constructor', { 
     value: this 
     }); 
     if (instance.initialize) { 
     instance.initialize.apply(instance, arguments); 
     } 
     return instance; 
    }, 
    defineMethod: function(name, body) { 
     this.prototype[name] = body; 
     return this; 
    }, 
    prototype: Object.create(superclass.prototype) 
    }; 
} 

var QuadTree = Class(BasicObjectClass); 
我跑的时候

,错误消息显示“遗漏的类型错误:无法读取属性“原型'未定义',不存在超类的原型。 这似乎是一个错误,但在这本书中没有关于 的任何解释。是否有人知道答案,为什么不正确,以及如何纠正它?非常感谢。

+0

如果你想要类的语法,使用ES6,这也应该做什么? – T4rk1n

+2

您在代码中定义了两次'Class'和'QuadTree'。不要这样做。 (提示:第二个'Class' *声明*被挂起,并用于第一个调用)。如果你从对方那里执行* 2 *片段,它就会起作用。 – Bergi

回答

2

因功能提升而陷入困境。你必须定义两个不同的功能有:

function Class() 

当你这样做的javascript“吊”这些顶端,这意味着第二个总是被调用。所以你第一次打电话...

var QuadTree = Class(); 

......你实际上正在调用第二个函数。由于您未传递参数,因此参数superclass未定义。这就是为什么重新使用函数名称是一个坏主意。

将第一个函数重命名为Class1(),并将呼叫更改为var QuadTree = Class1()使错误消失。

+0

+1不是说使用函数声明是个坏主意 :-) – Bergi