一.this 指针的理解
借鉴参考http://www.cnblogs.com/kongxy/p/4581223.html
this 是 js 的关键字,代表函数运行时,自动生成的一个内部对象。只能在函数内部使用。
this 指针至于函数的执行环境有关与声明环境无关
二.this 指针的四种调用方式
1.方法调用模式
当函数为一个对象属性的时候被称为方法, 当一个方法被调用时 this 绑定到这个对象上。如果被调用表达式有一个提取动作 点或者是[ ] 那么这样的就称之为方法调用模式。
<script>
let name = "window"
let obj1 = {
name: "obj1",
getname: function () {
return this.name
}
}
console.log(obj1.getname()) //obj1
//this会指向方法所在对象的name属性
</script>
2.函数调用模型
通过函数来调用 this,一般是绑定的是全局对象 window。
let name = "window";
function getname() {
console.log(this.name);
}
getname(); //window
单独一个函数直接调用的话,归类于 window 对象。
3.构造对象模型
在函数面前加一个 new,命名一个新的对象,那 this 就会指向这个新的对象,并且吧 name 属性赋值给这个新对象
function getname() {
this.name = "123";
}
let obj2 = new getname();
console.log(obj2); //Object { name: "123" }
使用 new 创建一个新对象,this 指向该对象
4. bind,call,apply
都可以改变 this 指针
格式都是.bind/apply/call(目标对象,属性值)
区别:bind只改变不执行,apply传入的为数组
function hello(name) {
// this:执行上下文,程序的运行环境
// this当前是window,全局
this.name = name;
// window.name=name
console.log(this);
}
hello("123");
const obj = {
name,
};
hello.bind(obj, "admin")(console.log(hello));
//name:admin
hello.call(obj, "111");
//name:111
hello.apply(obj, [222, 333]);
//222
本文介绍了JavaScript中的this关键字,它代表函数运行时的内部对象,与函数的执行环境相关而非声明环境。详细讨论了四种this的调用方式:方法调用模式(this绑定到对象)、函数调用模式(通常绑定到全局对象window)、构造函数模式(new操作符创建新对象时,this指向新对象)以及bind、call和apply方法(用于改变this指针)。
276

被折叠的 条评论
为什么被折叠?



