<script>
function Foo(i, j){
var i=i;
var j=j;
var a=3;
alert(i);
alert(this.i);
}
var foo = new Foo(1,2);
</script>
The result is "1" and "undefined",so we can conclude that the the "var i" is not a property belong to Object foo. It is a variable can be used in this function(notice:treat it as a function) ,but is not a property the class(I conside it as a java class).
<script>
function Foo(i, j){
var i=i;
var j=j;
var a=3;
alert(i);
alert(this.i);
}
var foo = new Foo(1,2);
</script>
In this way ,we declare a property named "i" of class Foo. and we can use the property of Object foo:
<script> alert(foo.i); </script>
本文通过一个JavaScript示例探讨了在构造函数中使用this关键字时,局部变量与对象属性之间的区别。解释了为什么局部变量不能直接作为对象的属性访问,并展示了如何正确地声明对象属性。
1万+

被折叠的 条评论
为什么被折叠?



