var a = 1; var b = 2;function changeValue(){ a = b;//上面的也可以说window.a=window.b; this.a = this.b;//changeValue的属性a和b } changeValue(); alert(window.a);//输出2 alert(changeValue.a);//undefined因为没有赋值 function changeValue(){ a = b;//上面的也可以说window.a=window.b; this.a = this.b;//changeValue的属性a和b } changeValue(); alert(window.a);//输出2 alert(changeValue.a);未定义因为没有赋值
var a = 1; var b = 2;function changeValue(){ a = b;//上面的也可以说window.a=window.b; this.a = this.b;//changeValue的属性a和b } changeValue(); alert(window.a);//输出2 alert(changeValue.a);//undefined因为没有赋值
this指向离他最近的function,如果没有function,则指向windowfunction changeValue(a){ this.a = a; }var test = new changeValue(1); alert(test.a);
一定要用class关键字的才叫class?你javascript代码用过new哇。 new Object()这种代码用过? 那alert(Object);打出来什么啊。你看过? 打出来的是 function Object{native code}javascript有类概念,这有什么好争得。没有类,哪来对象。 一味的强调对象,却否定类概念的存在,我服了
this是js中最为诡异的东西,和传统OOP软件完全不一样,具体见《javascript 真经》这本书,要弄明白是很麻烦的,我比较笨,通常是具体软件中,尽量不要this来this去,如果要作为对象对外提供接口时,拿不准时,alert看看,正确了继续写,嵌套时,把this保存起来,例如: function aa() { var mySelf=this; this.Name='xyz';
var a = 1;
var b = 2;function changeValue(){
a = b;//上面的也可以说window.a=window.b;
this.a = this.b;//changeValue的属性a和b
}
changeValue();
alert(window.a);//输出2
alert(changeValue.a);//undefined因为没有赋值
function changeValue(){
a = b;//上面的也可以说window.a=window.b;
this.a = this.b;//changeValue的属性a和b
}
changeValue();
alert(window.a);//输出2
alert(changeValue.a);未定义因为没有赋值
var a = 1;
var b = 2;function changeValue(){
a = b;//上面的也可以说window.a=window.b;
this.a = this.b;//changeValue的属性a和b
}
changeValue();
alert(window.a);//输出2
alert(changeValue.a);//undefined因为没有赋值
this.a = a;
}var test = new changeValue(1);
alert(test.a);
http://iamduyu.cn/?p=708
this必然生存在function里,怎么会没有function
如果该function没有挂靠在任何对象下,javascript规定,其this是指window自相矛盾。
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<script type="text/javascript">
alert(this === window);</script>
</head>
<body></body>
</html>上面这个this有function吗?
function getName() {
alert(this.name);
} function Test() {
this.getName = getName;
} var test = new Test();
test.name = '123';
test.getName();
你的话里有提到这种情况,这里第一个getName里的this指向最近的函数getName,但是在Test里,
getName又指向了Test的this
所以this链为 getName->Test.getName
这是用this实现对象冒充,是javascript实现继承的方法之一。
obj.method1=function(){this;};
this是指代method1这个function还是obj?
所以,this指代的是function挂靠的对象,而不是this生存所在的function本身,这是很根本的概念。
大哥我真服了你,我以为你blog里不写继承是你漏了,原来你不知道javascript的继承(对象冒充)。所以你一直不承认javascript的类概念
建议你打开www.baidu.com,键入对象冒充。
第一个getName中的this->第二个Test中的this->实例化test这个是this运行的顺序。
一定要用class关键字的才叫class?你javascript代码用过new哇。
new Object()这种代码用过?
那alert(Object);打出来什么啊。你看过?
打出来的是
function Object{native code}javascript有类概念,这有什么好争得。没有类,哪来对象。
一味的强调对象,却否定类概念的存在,我服了
全部看下来了,
书上有这么1句话,
JS里所有的function都是继承与object类
function aa()
{
var mySelf=this;
this.Name='xyz';
function bb()
{
alert(mySelf.Name);
}
}
这样就不容易混乱了