您的位置:首页 > Web前端 > JavaScript

js中this的知识点

2017-09-29 13:56 155 查看
1.this始终指向调用它的对象,但是难点就是判断这个对象是哪个;

(1)

function a(){
console.log(this===window)
}
a();
//true


(2)

function a(){
console.log(this===window)
}
function b(){
a();
}
b();
//true


(1)函数内部普通方式下,调用该段代码的直接对象是全局对象,即”window” ;(2)处虽然是函数,但是调用其的仍然是”window“(不要弄混了,函数虽然是对象,但是调用它的是另一个对象);没有实例引用所以还是指向window.

function a(){
return function(){
console.log(this===window);}
}
var b = a();
b();
//true


即使是return方式,this依然指向window.

function a(){
var b = function(){
console.log(this===window);
}
b();
}
a();
//true


函数内部嵌套,但是都指向window.原因是从最外层函数开始每层都是被window调用,即使你嵌套一千层,调用各个函数的都是’window’对象。

(3)

var test = function(){
al
4000
ert(this === window);
}
new test();
//false


这里test被看作构造函数,并创建了一个空的实例,所以this指向调用构造函数的这个实例

(4)

var test ={
'a':1,
'b':function(){
alert(this === test)
}
}
test.b();
//true


这里是对象引用的方式,而不是函数,’b’元素是一个函数,所以this指向的是对象test.

var test ={
'a':1,
'b':{
'c':function(){
alert(this === test)
}
}
}
test.b.c();
//false


this指向的是调用它的对象,所以这是是test.b调用的,this应该指向test.b

(5) call与apply

var test = function(){
alert(this === test1);
}
var test1 = {
}
test.apply(test1);
//true


call,apply都是test1调用test的,所以自然this会指向test1.

(6)原型

var test = function(){
}
var my = function(){
this.a = function(){
alert(this === mytest2);
}
}
var mytest = new my();
test.prototype = mytest;
var mytest2 = new test();
mytest2.a();


结果是true,首先this指向了实例mytest,然后被原型继承给test,原型继承,改变this指向,这样this就会指向test,最后又指向了test()的实例mytest2.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  javascript this