this

this

this –> 关键字; 在JS有特殊意义;
var a = 10;
/*console.log(this);
window.a = 10;
this.b = 18;*/

this的用法

函数中的this,指的是当前函数的执行主体;谁让函数执行的,那么this就指向谁;
  1. 在全局作用域下,this指向window;
  2. 函数体中的this,看函数执行前有没有”.”,如果有,那么点前面是谁,this就指向谁;如果没有“.”,那么会指向window;
  3. 如果给元素的事件行为绑定方法,那么方法中的this,就会指向当前被绑定的那个元素;
  4. 回调函数中的this指向window;
  5. 自执行函数中的this永远指向window;
  6. 构造函数中的this,指向实例
  7. call、apply、bind可以改变this指向

this的定义

  • this 是一个关键字,它代表当前函数的执行主体,谁执行函数,执行主体this就是谁。
  • this只能代表值,不能赋值
  • this的代表值取决于使用的场景,场景不同,this值就不同
// 构造函数
function Fn() {
//this --->实例
// 1.当代码执行之前,首先默认初始化一个空对象;
// 2.并且让构造函数中的this指向这个空间地址;
// 默认返回this;
// return this;
this.name = "";
this.down(this);
this.age = 18;
}
//let a = new Fn()// {} 实例;
/*Fn.prototype.down = function () {
}*/
Fn.prototype ={
down:function(a){
//this---实例
console.log(this);// 实例
console.log(this.constructor);//Object
//console.log(age);// 报错
console.log(this.age);// undefined
console.log(this.name);// ""
}
}
let a = new Fn();
//a.down();

 

this:在特殊场景下,指向不同的地址
posted @ 2018-08-11 00:09  席超  阅读(255)  评论(0编辑  收藏  举报