JS中this

来源:互联网 发布:php上传图片压缩大小 编辑:程序博客网 时间:2024/04/28 21:18

1 全局函数

alert(this);//[object, Window]

2

function test(){ alert(this);};//undefined

3 对象中的方法

var obj = {    name: 'obj对象',    test: function()    {        alert(this); //object Object        alert(this.name); //obj对象    }};obj.test();

结论: js中this永远指向属性或方法所属的对象

4 闭包中this

闭包函数属于全局

4.1

var name = 'this指向window对象';var obj = {    test: function()    {        return function(){            return this.name;        };    }};alert(obj.test()); //function(){return this.name};alert(obj.test()()); //this指向window对象

4.2 _this代替this

var name = 'this指向window对象';var obj = {    name: '_this指向局域变量',    test: function()    {        var _this = this;        return function(){            return _this.name;        };    }};alert(obj.test()()); //_this指向局域变量
0 0
原创粉丝点击