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

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 代表实参的个数
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  javascript this