this

this

函数执行的主体(不是上下文):意思是谁把函数执行的,那么执行主体就是谁

  1. 给元素的某个时间绑定方法,当事件触发方法执行的时候,方法中的this是当前操作元素本身

  2. 如何确定执行主体(this)是谁?当方法执行的时候,我们看方法前面是否有点,没有点this是window或者undefined;有点,点前面是谁this就是谁

    var name = 'zs'
    function fn(){
        console.log(this.name)
    }
    var obj = {
        name: 'ls',
        fn:fn 
    }
    obj.fn(); //=> this: obj   
    fn();     //=> this:window(非严格模式,严格模式下             手undefined)  window.fn()  window
                省略
    
    (function(){
        //=> 自执行函数中的this是window或undefined
    })()
    
    //=> hasOwnProperty方法中的this:ary.__proto__.__proto__
    ary.__proto__.__proto__.hasOwnProperty()
    
    let obj = {
        fn: (function(n)){
            //=>把自执行函数执行的返回结果赋值给fn
            //=>this: window
            return function(){
        	//=> fn等于这个返回的小函数
            //this:obj
           } 
        }(10)
    }
    
    obj:fn();
    
    function fn(){
        console.log(this)
    }
    
    document.body.onclick = function(){
    	fn() //=>this: window
    }
    
    1. 构造函数模式中,浏览器默认会创建一个对象数据类型的值,让函数体中的this指向这个对象

function CreatePerson(name, age) {
	// this=>person1
	this.name = name;
	this.age = age;
	// return 100; //=>返回的还是实例
	// return {
	// 	xxx: 'xxx'
	// }; //=>如果手动RETURN的是一个基本值,对返回的实例无影响,如果手动RETURN的是一个引用类型的值,会把默认返回的实例给替换掉(所以在构造函数模式执行下,我们一般都不要手动写RETURN,防止把返回的实例给替换)
}
let person1 = new CreatePerson('和冉', 18); */
posted @ 2020-08-21 18:00  TodoMt  阅读(46)  评论(0)    收藏  举报