我希望我的按钮能够调用绑定到它们的功能。有人可以解释一下这里出了什么问题吗?我已经将功能绑定到<button>
我用 Javascript 注入的一些元素,但看起来user.method
第 41 行正在返回undefined
。
http://codepen.io/ueeeieei/pen/KNQbXO?editors=0011
var $container = $('.container');
class User {
constructor(name, age, type) {
this.name = name;
this.age = age;
this.type = type;
}
sing() {
alert("singing");
console.log("singing");
}
sleep() {
alert("sleeping");
console.log("sleeping");
}
collectMethods() {
var methodNames = {
sing: "Sing",
sleep: "Sleep"
};
return methodNames;
}
}
function createButton(user) {
var methodNames = user.collectMethods();
for (var method in methodNames) {
var $btn = $('<button>' + methodNames[method] + '</button>');
$btn.bind("click", user.method);
$container.append($btn);
};
}
var udi = new User("Udi", 97.2, "In-Process");
var serj = new User("Serge", "30ish", "musico-programmer")
createButton(udi);
body {
background-color: rgba(0, 0, 0, .8);
color: white;
}
.container {
border: 1px solid white;
padding: 15px;
margin: 50px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<!-- content here -->
</div>