今天看到这样一种JS写法,该写法如下:
var C_C=function(){
var t=this;
t.div=document.getElementById('s');
t.div.c=t;
}
看的很晕啊!!!
这种JS写法怎样理解?这样写有问题吗?
var C_C=function(){
var t=this;
t.div=document.getElementById('s');
t.div.c=t;
}
看的很晕啊!!!
这种JS写法怎样理解?这样写有问题吗?
解决方案 »
- javascirpt引擎和javascirpt解析器是一个东西吗? 他们有关系吗
- 哪位老鸟能给个js代码
- 请问,如何改变网页上文本框中I型光标的颜色呢?
- 现在有什么好的方法获取客户端机器的MAC地址码
- 救命啊,关于document.domain的设置
- 为什么用正则表达式 ^\-{0,1}[0-9]+,{0,1}\.{0,1}[0-9]{0,}$ 验证 8,779.8 没有通过?怎么改?
- javascript修改table的问题
- 在TreeView中,如何利用javascript获取当前结点的父结点?
- 让当前窗口关闭的函数怎么写
- 谁能给我一个递归树的例子!
- jQuery中$定义问题
- JS中怎么把字符转为变量名使用?
function a(){
this.b=12;
var _this=this;
function c(){
alert(this.b);//undefined
alert(_this.b);//12
}
c();//这样调用c这个函数事实上c函数里的this指向的是window。而我们通过将_this=this;这样的话
_this只是一个局部变量。在c函数能访问外面的变量即_this这个局部变量。 javascript中如果调用一个函
数前没有对象,里面的this就是window. 比如调用d();如果d函数里有this那么this就是window。而如
果有则,this就是前面那个对象。比如a.b();则b中this就是a。
}
this.name = "abc";
this.age = 16; this.getName = function(){
return this.name;
}
this.getAge = function(){
return this.age;
}
} //使用 var s = new Student();
alert( s.getName() );
alert( s.getAge() );
var C_C=function() {} 这跟 function C_C() {} 是完全等同的var t=this; 这种写法我常用,特别是在事件应用的时候,因为this总是指向函数调用者,有时这种指向反而有些麻烦,而var t=this后,用t来代替this倒是很好的解决办法t.div=。 这个不用说了吧t.div.C=t; 这相当于说给那个div加个属性,引用t本身,以方便某处使用。
比如说在某处var d=document.getElementById('s'); 然后 var tt=div.C; 这样就得到C_C的那个实例了
直接使用this有什么弊端啊?
三楼的解释已经很清楚了
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>测试</title>
<script language="javascript" type="text/javascript">
function TestClass(ctrlID) {
this.ctrl = document.getElementById(ctrlID);
//this.ctrl.attachEvent("onkeypress", function() { this.OnKeyPress(); }); //方式一
//this.ctrl.attachEvent("onkeypress", this.OnKeyPress); //方式二
//方式三
//var t = this;
//this.ctrl.attachEvent("onkeyup", function() { t.OnKeyPress(); });
}
TestClass.prototype.OnKeyPress = function() {
var div = document.getElementById("output");
div.innerHTML = this.ctrl.value;
} window.onload = function() {
var test = new TestClass("inputBox");
}
</script>
</head>
<body>
<input id="inputBox" type="text" />
<div id="output"></div>
</body>
</html>
这里提供三种方式来使用事件,你觉得哪种可行呢?
上面两个弹出框的内容均为12,看来我又被this弄混了
你直接这样a();调用当然是全12呀,原因在于2个this都是window. 如果你new a();试试看是不是全12。 好好看看我的分析。希望对你有帮助. 帮助
觉得用在这里没有什么意义
比如这样可以
var C_C=function(){
this.name="C_C";
var t=this, div = document.getElementById('myDiv');
div.onclick=function(){
alert(t.name);
}
}
方式一的代码修改一下测试又出现一个疑问:
//this.ctrl.attachEvent("onkeypress", function() { alert(this.id); }); //方式一在IE下弹出undefined
//this.ctrl.addEventListener("keypress", function() { alert(this.id); },false); //方式一在FF下却弹出inputBox,
不明白为什么会这样?这里的this不是指input元素吗???
FF认为事件发生的时候,由发生事件的控件来调用注册的function(),所以this指向控件
而IE则由window来调用所注册的function(),所以this指向window,所以IE弹出undefined所以用方式三,就可以明确指定使用TestClass的实例
框架里都有绑定的方法
也可以这样
var me = this;
me.attachEvent('onclick', function(){
(function(){ alert(this.id)}).call(me)
})