var Student = function(name){
this.name = name;
}
Student .prototype.modifyName = function(){
var self = this;
$('#modify').click(function{
self.name = $('#text').val();
})
}
我怎么样才能在click的函数中使用this.name 是指向Student类的name。不需要我现在这样的写法(self.name),觉得比较土!
this.name = name;
}
Student .prototype.modifyName = function(){
var self = this;
$('#modify').click(function{
self.name = $('#text').val();
})
}
我怎么样才能在click的函数中使用this.name 是指向Student类的name。不需要我现在这样的写法(self.name),觉得比较土!
也就是这个onclick里面的东西是属于dom管的,对应的this自然是那个元素。
你要的也就是没法实现的
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=windows-31j">
<title>Insert title here</title>
<script type="text/javascript">
var Student = function(name){
this.name = name;
}
Student.prototype.modifyName = function() {
var test = document.getElementById("test");
var targetThis = this;
test.onclick = function() {
(function modify() {
alert(this.name);
}).call(targetThis);
};
}
window.onload = function() {
new Student("test").modifyName();
};
</script>
</head>
<body>
<input type="button" value="test" id="test"/>
</body>
</html>
利用call模拟实现,你可以重写jquery的addEventListener这个方法,然后把直接调用的地方全改成call