日期:2014-05-16 浏览次数:20398 次
function clickFun(value,elemID){
this._value = value;
this._elem = document.getElementById(elemID);
this._elem.ButtonFun = this;//this指向clickFun对象
this._elem.onclick = this.clickHandler;//来自与原型
}
clickFun.prototype.clickHandler = function(){
//这里为什么this是指向_elem的引用,即指向document.getElementById(elemID);
//因为clickHandler赋给了onclick,而onclick的调用者是_elem,所以他的执行上下文为_elem对象
//所以buttonFun是指向clickFun的引用
var buttonFun = this.ButtonFun;
var value = (buttonFun && buttonFun._value) ? buttonFun._value : "unknow value";
alert("value" + value);
alert("this.value" + this.value);
}
window.onload = function(){
new clickFun("赋给程序的值","bt");
}
<button type="button" value="我是按钮的值" id="bt">click me~</button>