JavaScript this 范围
看例子
<script type="text/javascript"> var f = function () { name = 'hongda'; age = 27; say = function () { console.log(this.name + "||" + this.age); } } var method = function () { name = 'hongda2'; age = 272; say = function () { console.log(this.name + "||" + this.age); } } </script>
由此可以看出这些name,age,say都是全局的,由window调用,say方法中的this就是window
<script type="text/javascript"> var f = function () { this.name = 'hongda'; this.age = 27; this.say = function () { console.log(this.name + "||" + this.age); } } </script>
调用的对象是f的实例
<script type="text/javascript"> var f = function () { name = 'hongda'; age = 27; say = function () { console.log(this.name + "||" + this.age); } } var method = function () { var name = 'hongda2'; var age = 272; var say = function () { console.log(this.name + "||" + this.age); } } </script>
发现method中的变量前有了 var,表示就在method这个范围内
下面将证明method中的name,age,say是局部的
发现method()实例化以后,全局的变量name,age,say没有发生变化
下面个例子可以看出function即是类,又是方法
<script type="text/javascript"> var f = function () { this.name = 'hongda'; this.age = 27; this.say = function () { console.log(this.name + "||" + this.age); } } </script>
var ff=new f(); f()是类
window.f(); f()是方法