gpt4 book ai didi

javascript - 值没有传递到类实例上

转载 作者:行者123 更新时间:2023-12-02 18:58:10 24 4
gpt4 key购买 nike

我有一个用 CoffeeScript 编写的非常简单的程序,如果用户单击按钮,则应在控制台中显示一个值。下面是我的代码:

HTML

<!DOCTYPE html>
<html>
<head>

</head>
<body>
<button id='butn'>click here</button>

<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
<script type="text/javascript" src="app.js"></script>
</body>
</html>

app.js 是编译后的 CoffeeScript。我的 CoffeeScript 如下:

init.coffee

init = =>

game = new Game()


# Start it all off
$(document).ready(init)


<小时/>
游戏.咖啡

class Game

constructor: () ->

@UI = new UI()


<小时/>
ui.coffee

class UI

constructor: () ->

@toolbar = new Toolbar('foo')


<小时/> 工具栏.coffee

class Toolbar
constructor: (@value) ->

@clickhandler()


clickhandler: () =>
$('body').on 'click', '#butn', ->
console.log 'Value = ', @value


<小时/>

编译后的 JS 是:

// Generated by CoffeeScript 1.3.3
(function() {
var Game, Toolbar, UI, init,
_this = this,
__bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; };

init = function() {
var game;
return game = new Game();
};

$(document).ready(init);

Game = (function() {

function Game() {
this.UI = new UI();
}

return Game;

})();

UI = (function() {

function UI() {
this.toolbar = new Toolbar('foo');
}

return UI;

})();

Toolbar = (function() {

function Toolbar(value) {
this.value = value;
this.clickhandler = __bind(this.clickhandler, this);

this.clickhandler();
}

Toolbar.prototype.clickhandler = function() {
return $('body').on('click', '#butn', function() {
return console.log('Value = ', this.value);
});
};

return Toolbar;

})();

}).call(this);


<小时/>

问题

值“foo”未显示在控制台上。控制台记录“Value =”,但没有记录“foo”。请有人帮助我理解为什么以及如何在不改变太多程序的情况下解决这个问题。

感谢您的所有帮助。

最佳答案

您的问题是 this keyword 的值在事件处理程序内部,它指向 DOM 元素而不是 Toolbar 实例。使用function binding :

class Toolbar
constructor: (@value) ->
@clickhandler()

clickhandler: () ->
$('body').on 'click', '#butn', =>
console.log 'Value = ', @value

关于javascript - 值没有传递到类实例上,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15111969/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com