js 的 this 到底是谁??? js 中函数的4中调用方式
1). 作为普通函数来调用
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
|
console.log(window.xxx); function t() { this.xxx = 333; }
t(); console.log(window.xxx);
function test() { console.log(this.test_window); } test();
|
作为对象的方法来调用
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
|
var obj = { xx: 99, yy: 88, t: function () { console.log(this.xx); } }; obj.t();
var dog = {xx: 'wangwang'}; dog.t = obj.t; dog.t();
show = function () { console.log('show' + this.xx); } dog.t = show; dog.t();
|
函数作为构造函数调用时
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
|
function Dog(name, age) { this.name = name; this.age = age; this.bark = function () { console.log('this is ' + this.name); } }
var dog = new Dog('huzi', 2); dog.bark();
function Pig() { this.age = 99; return 'abc'; }
var pig = new Pig(); console.log(pig);
|
函数通过 call , apply 调用
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
|
function t(num) { console.log('我的真实年龄是' + this.age); console.log('但是我一般告诉别人我' + (this.age + num)); }
var humanObject = {name: 'lisi', age: 28};
humanObject.t = t; humanObject.t(-10);
var wangwuObject = {name: 'wangwu', age: 30}; t.call(wangwuObject, 5);
|
demo 练习
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| name = 'this is window';
var obj = { name: 'php', t: function () { console.log(this.name) } }; var dog = {name: 'huzi'}; obj.t();
var tmp = obj.t; tmp();
dog.t = obj.t; dog.t();
(dog.t = obj.t)(); (function(){console.log(this.name)})();
|
其他 window 全局变量污染