我收到了错误:
Uncaught TypeError: Cannot read property 'constructor' of undefined
声明以下课程时:
class ViewHelpers extends Backbone.Events
我可以使用相同的语法来扩展Backbone.Router,Views,Model等。这是我在快速日志中编写的已编译的javascript,以确保Backbone.Events存在
__t('views').ViewHelpers = (function(_super) {
#how i know it is definied here
console.log(_super.trigger)
__extends(ViewHelpers, _super);
function ViewHelpers() {
return ViewHelpers.__super__.constructor.apply(this, arguments);
}
return ViewHelpers;
})(Backbone.Events);
因此导致错误的行是
ViewHelpers.__super__.constructor.apply(this, arguments);
__extends()方法有什么不同,它适用于Backbone.View而不是Backbone.Events?
答案 0 :(得分:38)
那是因为Backbone.Events
不是“类”,所以它不能被扩展,它是一个可以混合到其他对象中的“模块”(参见文档here)。在JavaScript术语中,这意味着它不是Function
,可以作为构造函数调用(即new Backbone.Events
将抛出错误),它只是一个普通的JS对象,其属性(方法)可以分配给其他对象使它们成为事件调度程序。
在CoffeeScript中,您可以在创建对象时将Backbone.Events
混合到对象中:
class ViewHelpers
constructor: ->
_.extend @, Backbone.Events
或者您可以扩展类的原型并避免将这些方法作为所有ViewHelpers
实例的(自己)属性:
class ViewHelpers
_.extend @prototype, Backbone.Events
这两种方法应该有效,让您实例化并使用ViewHelpers作为事件调度程序:
vh = new ViewHelpers
vh.on 'foo', -> alert 'bar'
vh.trigger 'foo'
答案 1 :(得分:1)
还有另一种方式(来自@epidemian的回答),它不涉及将Backbone.Events
复制到一个新对象中用作原型 - 而是使用Object.create
创建一个新对象来使用作为您的原型,使用Backbone.Events
作为其原型。
class ViewHelpers
@prototype = Object.create(Backbone.Events)
现在ViewHelpers
'原型是一个新的空对象,其原型为Backbone.Events
。您可以在ViewHelpers
'原型上定义方法而不会影响Backbone.Events
,但所有Backbone.Events
方法仍可供ViewHelpers
使用,而无需将其复制到新对象中。这不仅可以节省(微不足道的数量)内存,而且如果您最后添加到Backbone.Events
,则所有ViewHelpers
都会看到更改。
为此,您需要a browser that has ES5's Object.create
function或an Object.create
polyfill。
答案 2 :(得分:0)
为了建立@epidemian的优秀答案,我会添加它,它有点像黑客,但它允许你用你在问题中指定的extends
语句编写你的类(允许您在所有super
方法上调用Backbone.Events
:
class Events
_.extend Events.prototype, Backbone.Events
class CustomEvents extends Events
trigger: (event, etc...) ->
# You can add overrides before
super "custom:#{event}", etc...
# or after the super class methods
将_.extend
调用Events.constructor
调用# PowerShell code...
query session /server:"SERVERNAME" #NEEDS ELEVATED PERMISSIONS
# More PowerShell code
函数会很好,但我无法使其正常工作......