js中的this关键字详解

来源:互联网 发布:沈阳系统i5编程实例 编辑:程序博客网 时间:2024/05/17 03:09

随着函数使用场合的不同,this的值会发生变化。但是有一个总的原则,那就是this指的是,调用函数的那个对象。

//函数内部调用var boat = {    size: 'normal',    boatInfo: function() {    alert(this === boat);    alert(this.size);    }};boat.boatInfo(); // true, 'normal'var bigBoat = {    size: 'big'};bigBoat.boatInfo = boat.boatInfo;bigBoat.boatInfo(); // false, 'big'
// 全局作用域foo = 'abc';alert(foo); // abcthis.foo = 'def';alert(foo); // def
//作为构造函数调用   function test(){     this.x = 1;   }   var o = new test();   alert(o.x); // 1 
0 0
原创粉丝点击