this

this

this代表一个对象,常常在项目中我们要给对象操作属性

this指向的是调用者

在全局作用域下普通函数指向的是window

定时器里面的this也是指向window

fn() // window
obj.fn() // obj
obj.xx.fn() // obj.xx
(function() {})() // window
fn()() // window
fn()[2]() // fn()返回的数组
obj.fn(this) // window
  1. 看this在那个那个函数里面,离this这个单词最近(嵌套)的function方法这个单词就是那个函数,没有就是window
  2. 这个函数找到了,是那个代码让这个函数执行的,辨别调用者和持有者
function fn() {
    var a = 20;
    var arr = [function() {}];
    var obj = {bg:function() {
        console.log(bg); // 没有
    }}
}
function Foo() {
    getName = function() {console.log(1)};
    reture this;
}
var getName = function() {console.log(4)}
Foo().getName();
// 函数里1的覆盖了外面的4
// 1
function a(xx) {
    this.x = xx;
    return this;
};
var x = a(5);
// var xx = 5; window.x = 5; reture window; 
// window.x = window 
var y = a(6);
// var xx = 6; window.x = 6; returen window
// window.x = 6,x.x 为undefined
// window.y = window
console.log(x.x);	// undefined
console.log(y.x);  // 6

基本数据取一个不存在的值会返回undefined

var a = {n:1};
var b = a;
a.x = a = {n:2};
console.log(a.x); //undefined
console.log(b.x); // object n:2
posted @ 2022-08-29 11:03  a立方  阅读(117)  评论(0编辑  收藏  举报