javascript中this的妙用

this是javascript语言的一个关键字,它代表函数运行时,自动生成的一个内部对象,只能在函数内部使用。

this总是指向对象,并且为调用函数的那个对象;

//调用普通函数
function fn() {
    document.write(this);                 //[object Window]
    document.write(this.constructor);     //[object Window]
}
var o = fn(); //window.fn()

//调用对象函数
function fn() {
    document.write(this);                 //[object Object]  
    document.write(this.constructor);     //function fn(){code}  
}
var o = new fn(); 	

分解var o = new fn();

1.先创建新的对象,并把这个对象赋给变量o:var o = {};
2.然后再调用函数fn():fn.call(o);  

完整结构如下:
function fn() {
    document.write(this);                 //[object Object]  
    document.write(this.constructor);     //function Object() { [native code] } 
}
var o = {};
fn.call(o); //调用fn方法的是o对象,所以当前的对象(this)为([object Object])


一般对象的声明方式:
var o = window.o || {};
o.fn = function(p){
    document.write(this);                 //[object Object]  当前对象为o
}
原文地址:https://www.cnblogs.com/sntetwt/p/3298932.html