javascript中,关于使用this的问题
在下面的代码中,想要点击button的时候alert显示t.testName的值,但是:
button1.onclick=function()
{
alert(this.testName);
}
这样好像不对,应该怎么写才可以呢?
完整代码如下:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN " "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd ">
<html xmlns= "http://www.w3.org/1999/xhtml ">
<head>
<meta http-equiv= "Content-Type " content= "text/html; charset=utf-8 " />
<title> Untitled 1 </title>
<script type= "text/javascript ">
function test(newName)
{
this.testName = newName;
}
test.prototype.testClick=function()
{
var button1 = document.getElementById( "button1 ");
button1.onclick=function()
{
alert(this.testName);
}
}
</script>
</head>
<body>
<button id= "button1 "> test </button>
<script type= "text/javascript ">
var t = new test( 'Andy ');
t.testClick();
</script>
</body>
</html>
------解决方案-------------------- <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN " "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd ">
<html xmlns= "http://www.w3.org/1999/xhtml ">
<head>
<meta content= "text/html; charset=utf-8 " http-equiv= "Content-Type " />
<title> Untitled 1 </title>
<script type= "text/javascript ">
var Class = {
create : function () {
return function () {
this.initialize.apply (this,arguments);
}
}
}
var $ = function (id) {
return document.getElementById(id);
}
var test = Class.create();
test.prototype = {
initialize : function (name) {
var t = this;
t.testName = name;
},
testName : null,
testClick : function (btnid) {
var t = this;
var button1 = $(btnid);
button1.onclick = function () {
alert(t.testName);
}
}
}
</script>
</head>
<body>
<button id= "button1 ">
test </button>
<script type= "text/javascript ">
var t = new test( 'Andy ');
t.testClick( 'button1 ');
</script>
</body>
</html>
------解决方案--------------------因为js是动态解释的,所以函数由哪个对象触发,this就指向那个对象~~~
相对于预编译的语言~这点很有特色~~~
------解决方案--------------------789的代码虽然好,但是不是太容易理解,主要就是那一句t=this这句,按照你的代码改下的话就是
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN " "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd ">
<html xmlns= "http://www.w3.org/1999/xhtml ">
<head>
<meta http-equiv= "Content-Type " content= "text/html; charset=utf-8 " />