function TextInfo(element, info) { this._textBox = element; this.text = info; this._textBox.value = info; this._textBox.onblur = new createDelegate(this, this._onblur); this._textBox.onfocus = new createDelegate(this, this._onfocus); } TextInfo.prototype = { _onblur: function () { if (this._textBox.value.length == 0) { this._textBox.value = this.text; } }, _onfocus: function () { if (this._textBox.value.length != 0 && this._textBox.value == this.text) { this._textBox.value = ""; } } }
//方法委托,确保this关键字作用域正确。 createDelegate = function(instance, method) { return function () {
//指定方法调用者 return method.apply(instance, arguments); } }
调用:new TextInfo(document.getElementById("textMarks"), "请输入用户名");