console.log t() "no" 它将编译为如下内容: (function()-6ren">
gpt4 book ai didi

javascript - CoffeeScript 和 OOP - 原型(prototype)方法

转载 作者:行者123 更新时间:2023-11-28 11:17:24 24 4
gpt4 key购买 nike

假设我执行以下代码:

class Test
t: ->
"hell"
d: ->
console.log t()
"no"

它将编译为如下内容:

(function() {
this.Test = (function() {
function Test() {}
Test.prototype.t = function() {
return "hell";
};
Test.prototype.d = function() {
console.log(t());
return "no";
};
return Test;
})();
}).call(this);

好的,我无法在 d() 方法中调用 t() 方法。

为什么不呢?我该如何修复它?

提前致谢。

最佳答案

class Test
t: ->
"hell"
d: ->
console.log @t()
# ^ Added
"no"

在 CoffeeScript 中,就像在 Javascript 中一样,原型(prototype)上的方法必须作为 this 的属性进行访问。 CoffeeScript 有 this 的简写,即 @ 字符。 @t() 编译为 this.t()this.t() 将在您调用它的实例的上下文中执行 Test.prototype.t()

关于javascript - CoffeeScript 和 OOP - 原型(prototype)方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14346574/

24 4 0
文章推荐: ios - UILocalNotification 声音不工作
文章推荐: css - HTML5/CSS : possible to define a