THIS的几种基本情况

238 阅读2分钟
/*
 * THIS的几种基本情况
 *   + 事件绑定
 *   + 函数执行
 *     + 匿名函数
 *     + 成员访问
 *     + 普通函数
 *     + 回调函数
 *     + ...
 *   + ... 
 */
// "use strict"//严格模型
//console.log(this);//全局下的this是window对象{GO};块级私有上文中没有自己THIS是"宿主环境"中的;所以我们研究的THIS都是指:函数执行,产生的私有上下文中的THIS;
// THIS:函数的执行主体"谁把它执行的",和函数中哪里创建以及中哪执行没啥关系!!以后遇到的this,想起周妈的一句话"你以为你以为的就是你以为的",冷静、冷静、冷静...按住我们总结的规律去套即可!!
//      @1给当前元素的某一个事件行为绑定方法,当事件行为触发,浏览器会帮我们把绑定的方法执行,此时方法中的this是当前操作的元素本身
//      @2函数执行,看函数前面是否有'点'
//          +没有:非严格模式下this->window 严格模式下this->undefined
//          +有:"点"前面是谁this就是谁
// const fn = function fn(){
//     console.log(this);
// }
// let obj={
//     name:'OBJ',
//     // fn:fn ES6语法中如果属性名和属性值的变量名字相同,我们可以像以下这样简写
//     fn
// };
// document.body.onclick=function(){
//     // this->body
//     fn();//this->undefined
// }

// document.body.onclick=fn;//this -> body
// fn();//this->undefined
// obj.fn();//this->obj

// let arr=[10,20],
//     push=arr.push;
//     push();//this->undefined
//     arr.push();//this->arr
//     arr._proto_.push();//this->arr._proto_
//     Array.prototype.push();//this-> Array.prototype

// =========AA


// let x = 3,
//     obj = {
//         x: 5
//     };
// obj.fn = (function () {
//     this.x *= ++x;
//     return function (y) {
//         this.x *= (++x) + y;
//         console.log(x); 
//     }
// })();
// let fn = obj.fn;
// obj.fn(6);
// fn(4);
// console.log(obj.x, x);

let x =5;
const fn=function fn(x){
    return function(y){
        console.log(y+(++x));
    }
};
let f = fn(6);
f(7);//14
fn(8)(9);//18
f(10);//18
console.log(x);//5





/* let obj = {
    fn: (function () {
        return function () {
            console.log(this);
        }
    })()
};
obj.fn();
let fn = obj.fn;
fn(); */


/* var fullName = 'language';
var obj = {
    fullName: 'javascript',
    prop: {
        getFullName: function () {
            return this.fullName;
        }
    }
};
console.log(obj.prop.getFullName());
var test = obj.prop.getFullName;
console.log(test()); */


/* var name = 'window';
var Tom = {
    name: "Tom",
    show: function () {
        console.log(this.name);
    },
    wait: function () {
        var fun = this.show;
        fun();
    }
};
Tom.wait(); */


/* window.val = 1;
var json = {
    val: 10,
    dbl: function () {
        this.val *= 2;
    }
}
json.dbl();
var dbl = json.dbl;
dbl();
json.dbl.call(window);
alert(window.val + json.val); */


/* (function () {
    var val = 1;
    var json = {
        val: 10,
        dbl: function () {
            val *= 2;
        }
    };
    json.dbl();
    alert(json.val + val);
})(); */