js中this的知识点
2017-09-29 13:56
155 查看
1.this始终指向调用它的对象,但是难点就是判断这个对象是哪个;
(1)
(2)
(1)函数内部普通方式下,调用该段代码的直接对象是全局对象,即”window” ;(2)处虽然是函数,但是调用其的仍然是”window“(不要弄混了,函数虽然是对象,但是调用它的是另一个对象);没有实例引用所以还是指向window.
即使是return方式,this依然指向window.
函数内部嵌套,但是都指向window.原因是从最外层函数开始每层都是被window调用,即使你嵌套一千层,调用各个函数的都是’window’对象。
(3)
这里test被看作构造函数,并创建了一个空的实例,所以this指向调用构造函数的这个实例
(4)
这里是对象引用的方式,而不是函数,’b’元素是一个函数,所以this指向的是对象test.
this指向的是调用它的对象,所以这是是test.b调用的,this应该指向test.b
(5) call与apply
call,apply都是test1调用test的,所以自然this会指向test1.
(6)原型
结果是true,首先this指向了实例mytest,然后被原型继承给test,原型继承,改变this指向,这样this就会指向test,最后又指向了test()的实例mytest2.
(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.
相关文章推荐
- JS递归、闭包、this
- 轻松拿下JavaScript(四)——对象字面量,this,call()和apply()方法,JS的异常处理
- js中this的使用
- js 函数作用域与this 的指向实例
- js小知识点
- js中的this
- js 知识点
- js--关于this
- js中this指向问题
- 详解照片瀑布流效果(js,jquery分别实现与知识点总结)
- JS 中的 this 机制
- JS的this本质
- 关于js里的this关键字的理解
- JS知识点
- js闭包的理解以及闭包中this的理解
- css+js初步知识点总结
- js知识点图解
- 彻底理解js中this的指向,不必硬背。
- Js-----var x, this.x, x....inheritance
- js中with、this的用法