javascript - CoffeeScript 类变量

标签 javascript class variables coffeescript

class Example
  constructor: ->
    $.each [1, 2, 3], (key, value) ->
      @test = value
    return @test
  render: ->
    alert @test

example = new Example()
example.render()​​​​​​​​​​​​​​​​​​​​​​

我正在使用 CoffeeScript (+ jQuery),这是一个类示例,我将在 @test 变量中获取值 3。但这并没有发生,你能帮助我吗?

最佳答案

这是一个范围界定问题: $.each 接受一个函数,该函数在作用域内,因此,您的 this 变量不是您期望的变量。

工作代码:

class Example
  constructor: ->
    $.each [1, 2, 3], (key, value) =>
      @test = value
    return @test
  render: ->
    alert @test

example = new Example()
example.render()​​​​​​​​​​​​​​​​​​​​​​

什么改变了?检查 $.each 调用上的箭头,它现在是一个粗箭头。粗箭头的技巧是设置一个 _this 变量,并在使用 @... 时使用它,使您的作用域成为您期望的作用域。

检查http://coffeescript.org有关更多详细信息,请参阅“函数绑定(bind)”部分!

关于javascript - CoffeeScript 类变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10073309/

相关文章:

javascript - Firefox ES6,获取类构造函数名称

c++ - c++中如何调用不同类的函数?

c++ - 如何在 C++ 中使用另一个类的值?

javascript - 从 JavaScript 调用 ASP.NET 代码隐藏方法

javascript - float 标记函数,轴未定义?

javascript - 更改 document.form1.Q1[n+1].value 中的变量

java - 使用接口(interface)而不是类来定义泛型

javascript - 我如何像 React 一样在 Angular 2+ 中传递 Prop ?

c# - 在 mvvm 问题中创建类结构

用于检查/分配变量的 c# 习语