发表于: 2017-05-01 23:18:37
1 1019
一、今天完成的事情
今天电脑出了点问题,明天拿去修,完成了流程页面和杀人页面的关联。
二、明天计划的事情
继续任务4
三、遇到的问题
JS中this的指向?
全局环境中this指向window。
//直接打印
console.log(this) //window
//function声明函数
function bar () {console.log(this)}
bar() //window
//function声明函数赋给变量
var bar = function () {console.log(this)}
bar() //window
//自执行函数
(function () {console.log(this)})(); //window
2.谁调用指向谁
//对象方法调用
var person = {
run: function () {console.log(this)}
}
person.run() // person
//事件绑定
var btn = document.querySelector("button")
btn.onclick = function () {
console.log(this) // btn
}
//事件监听
var btn = document.querySelector("button")
btn.addEventListener('click', function () {
console.log(this) //btn
})
//jquery的ajax
$.ajax({
self: this,
type:"get",
url: url,
async:true,
success: function (res) {
console.log(this) // this指向传入$.ajxa()中的对象
console.log(self) // window
}
});
//这里说明以下,将代码简写为$.ajax(obj) ,this指向obj,在obj中this指向window,因为在在success方法中,独享obj调用自己,所以this指向obj
3.在构造函数中this指向本身
//不使用new指向window
function Person (name) {
console.log(this) // window
this.name = name;
}
Person('inwe')
//使用new
function Person (name) {
this.name = name
console.log(this) //people
self = this
}
var people = new Person('iwen')
console.log(self === people) //true
//这里new改变了this指向,将this由window指向Person的实例对象people
四、收获
学习JS中this的指向
评论