[英]Store function reference in javascript object
我猜這應該很簡單,但是我被卡住了。 如何在另一個原型對象中存儲對方法的引用(在這種情況下為actions
)? 在下面的方式中,我的someFn和anotherFn方法未定義。
class MyClass
constructor: ->
console.log @actions # returns
# returns:
# Object {someFn: undefined, anotherFn: undefined, someText "I am some text"}
actions:
someFn: @someFn
anotherFn: @anotherFn
someText: 'I am some text'
someFn: ->
console.log 'I am some function'
anotherFn: ->
console.log 'I am another function'
我正在使用CoffeeScript,但是對於任何普通的JSers來說,我們都可以-
MyClass = function MyClass() {
console.log(this.actions);
}
MyClass.prototype.actions = {
someFn: MyClass.someFn,
anotherFn: MyClass.anotherFn,
someText: 'I am some text'
};
MyClass.prototype.someFn = function() {
return console.log('I am some function');
};
MyClass.prototype.anotherFn = function() {
return console.log('I am another function');
};
原型上不能有這樣的對象。 您需要將該實例屬性設置為:
class MyClass
constructor: ->
@actions =
someFn: @someFn
anotherFn: @anotherFn
someText: 'I am some text'
console.log @actions # works as expected
someFn: ->
console.log 'I am some function'
anotherFn: ->
console.log 'I am another function'
如果由於某種原因您確實需要帶有原型功能的對象,請使用::
來訪問它們(在創建action
對象的靜態上下文中):
…
someFn: …
anotherFn: …
actions:
someFn: @::someFn
anotherFn: @::anotherFn
someText: 'I am some text'
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.