我明白call的意思,但实在看不懂鼠标单击的时候竟然获取到obj对象的属性,觉得很神奇。
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"><html>
<head>
<META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=UTF-8">
<script>function init()
{
var obj = new Obj("subdiv");
obj.draw();
}function Obj(name)
{
this._name = name;
}Obj.prototype.draw = function()
{
var basediv = document.getElementById("baseDiv");
var subdiv = document.createElement("div");
subdiv.style.left = "100px";
subdiv.style.top = "50px";
subdiv.style.width = "200px";
subdiv.style.height = "100px";
subdiv.style.border = "1px solid black";
subdiv.style.position = "absolute";
var instance = this;
subdiv.onclick = function( e ) { instance.objClickEvent.call( instance, e ); };
basediv.appendChild(subdiv);
}Obj.prototype.objClickEvent = function( e )
{
alert( this._name );
}window.onload=init;
</script>
</head>
<body>
<div id="baseDiv" style="position:relative;border:1px solid black;width:600px;height:300px;">
</div>
</body>
</html>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"><html>
<head>
<META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=UTF-8">
<script>function init()
{
var obj = new Obj("subdiv");
obj.draw();
}function Obj(name)
{
this._name = name;
}Obj.prototype.draw = function()
{
var basediv = document.getElementById("baseDiv");
var subdiv = document.createElement("div");
subdiv.style.left = "100px";
subdiv.style.top = "50px";
subdiv.style.width = "200px";
subdiv.style.height = "100px";
subdiv.style.border = "1px solid black";
subdiv.style.position = "absolute";
var instance = this;
subdiv.onclick = function( e ) { instance.objClickEvent.call( instance, e ); };
basediv.appendChild(subdiv);
}Obj.prototype.objClickEvent = function( e )
{
alert( this._name );
}window.onload=init;
</script>
</head>
<body>
<div id="baseDiv" style="position:relative;border:1px solid black;width:600px;height:300px;">
</div>
</body>
</html>
保存了draw的实体指针this.
call调用function,并将function里的this指为obj,其余的为传递给function的参数
而且还是自己指自己的那中!~
{
alert( this._name );
}