js中this的指向问题
2017-05-20 22:48
896 查看
1 函数四种调用模式:
// 1 函数调用模式 // 2 方法调用模式 // 3 构造函数调用模式 // 4 借用方法调用模式(上下文调用模式) // call / apply // 这 4种模式 就是按照函数内部 this 指向的不同来区分的!!!
2 分析this的问题只需要明白两点:
// 1 分析 this 是属于哪个函数 // 2 分析该函数是以什么模式被调用的 // // 分析 this 的问题,只看函数是怎么被调用的,不管函数是怎么来的!
1 函数调用模式:this —-> window
// var fn = function() { // console.log( this ); // }; // fn();
2 方法调用模式:this —-> 当前对象(调用方法的对象)
// var obj = { // name: '饿了吗??', // fn: function() { // console.log( this ) // } // }; // obj.fn();
3 构造函数调用模式: this —-> 该构造函数的实例对象
var Person = function() { // console.log( this ) console.log( this instanceof Person ); }; Person.prototype.say = function() { // this ----> 实例对象p console.log( this === p ); }; var p = new Person(); p.say();
4 借用方法调用模式:call / apply
// 作用:调用函数,并且在调用函数的同时可以修改函数内部this的指向 // 语法:函数名.call() / 函数名.apply() // call 和 apply 是由 Function.prototype 来提供的 // console.dir( Function.prototype ); // apply方法,有两个参数:两个参数都是可以省略的 // 第一个参数:表示函数内部this的指向,实际上就是让第一个参数表示的对象来调用该方法! // 第二个参数:是一个数组或者伪数组,数组或伪数组中的每一项元素会作为被调用方法的参数 // apply可以传数组或者伪数组,call只能传单个参数
补充扩展arguments
arguments.callee() 函数自调用arguments.length 代表实参的个数
相关文章推荐
- 聊一聊JS中this的指向问题
- 详解JS中定时器setInterval和setTImeout的this指向问题
- js绑定事件this指向发生改变的问题解决方法
- js中this的应用及指向问题
- js中this指向问题
- 彻底理解JS中This指向问题
- js 深入理解this指向问题
- js中的this指向问题
- JS中各种this指向问题
- js中this的应用及指向问题
- js中的this指向问题及解决方案
- what's this? 浅谈js中this的指向问题
- js addEventListener和attachEvent函数中的this的指向问题及解决方法
- 关于js中的this的指向问题(一)
- Js中的this指向问题
- 如何理解JS中的this指向问题
- JS中的this 指向问题
- Js中的this指向问题(2)
- 解决js绑定事件this指向发生改变的问题
- js中this指向问题