美文网首页
JS中this关键字详解

JS中this关键字详解

作者: 小龙虾Julian | 来源:发表于2020-04-21 13:48 被阅读0次
1、JS中函数的几种调用方式

(1)普通函数调用
(2)作为对象方法调用
(3)作为构造函数调用
(4)apply/call方法调用
(5)Function.ptototype.bind()方法
(6)ES6箭头函数
总之:无论谁调用这个函数或方法this就指向谁

2、调用方式实例与解析

(1)普通函数调用

function person(){
    this.name="hello";
    console.log(this);       // window
    console.log(this.name);     // hello
}
person();

解析:person函数作为普通函数调用,实际上person是作为window全局对象的一个方法进行调用的,即window.person(),所以window对象调用了person方法,那么person函数中的this就指向window,同事window还拥有了另外一个属性name,值为hello

(2)作为对象方法调用

var name = "HELLO";
var person = {
    name:"hello",
    showName:function(){
        console.log(this.name);
    }
}
foo.showName();      //这里是person对象调用showName方法,很显然this关键字是指向person对象的,因此输出hello
var showNameA = person.showName;
showNameA();     //这里将person.showName方法赋给showNameA变量,此时showNameA变量相当于window对象的一个属性,因此showNameA()执行的时候相当于window.showNameA(),即window对象调用showNameA这个方法,所以this关键字指向window,因此输出HELLO
var personA = {
    name: "hello",
    showName: function(){
        console.log(this.name);     // HELLO
    }
}
var personB = {
    name: "HELLO",
    sayName: personA.showName
}
personB.sayName();  //虽然showName方法是在personA这个对象中定义,但是调用的时候却是在personB这个对象中调用,因此this对象指向personB,因此输出HELLO

(3)作为构造函数调用

function Person(name){
    this.name = name;
}
var personA = Person("hello");  
console.log(window.name);     //此处没有进行new操作,相当于window对象调用Person("hello")方法,此时this指向window对象,并进行赋值操作window.name = "hello"
var personB = new Person("hello");
console.log(personB.name);     // hello
function person(name){//new操作符(实例化对象)的内部过程
    var o = {};
    o.__proto__ = Person.prototype;  //原型继承
    Person.call(o,name);
    return o;
}
var personB = person("hello");
console.log(personB.name);  //hello  

解析:在person里面首先创建一个空对象o,将o的proto指向Person.prototype完成对原型的属性和方法的继承;Person.call(o,name)这里即函数Person作为apply/call调用(具体内容下方),将Person对象里的this改为o,即完成了o.name=name操作;返回对象o;因此 person("hello") 返回了一个继承了Person.prototype 对象上的属性和方法,以及拥有 name 属性为"hello"的对象,并将它赋给变量personB,所以 console.log(personB.name) 会输出 hello

(4)apply/call方法调用:在JS里函数也是对象,因此函数也有方法。从Function.prototype上继承了Function.prototype.call/Function.prototype.apply方法,call/apply方法最大的作用就是能改变this关键字的指向

var name="HELLO";
var Person={
    name: "hello",
    showName: function(){
        console.log(this.name);
    }
}
Person.showName.call(); //call方法里面的第一个参数为空,默认指向window。虽然showName方法定义在Person对象里面,但是使用call方法后,将showName方法里面的this指向了window。因此输出"HELLO";
function FruitA(n1, n2){
    this.n1 = n1;
    this.n2 = n2;
    this.change = function(x,y){
        this.n1 = x;
        this.n2 = y;
    }
}
var fruitA = new FruitA("cheery","banana");
var FruitB = {
    n1: "apple",
    n2: "orange"
};
fruitA.change.call(FruitB,"pear","peach");
console.log(FruitB.n1);      //FruitB调用fruitA的change方法,将fruitA中的this绑定到对象FruitB上,因此输出pear
console.log(FruitB.n2);     //FruitB调用fruitA的change方法,将fruitA中的this绑定到对象FruitB上,因此输出peach

(5)Function.ptototype.bind()方法

var name = "HELLO";
function Person(name){
    this.name = name;
    this.sayName = function(){
        setTimeout(function(){
            console.log("my name is "+this.name);
        },50)
    }
}
var person = new Person("hello");
person.sayName()     //setTimeout()定时函数相当于window.setTimeout(),由window这个全局对象对调用,因此this的指向为window,,则this.name则为 HELLO
var name = "HELLO";
function Person(name){
    this.name = name;
    this.sayName = function(){
        setTimeout(function(){
            console.log("my name is "+this.name);
        }.bind(this),50)  //注意这个地方使用的bind()方法,绑定setTimeout里面的匿名函数的this一直指向Person对象
    }
}
var person = new Person("xl");
person.sayName();     //setTimeout(function(){console.log(this.name)}.bind(this),50);,匿名函数使用bind(this)方法后创建了新的函数,这个新的函数不管在什么地方执行,this都指向的Person,而非window,因此最后的输出为"my name is hello"而不是"my name is HELLO"

解析:setTimeout/setInterval 匿名函数执行的时候,this默认指向window对象,除非手动改变this的指向。在《javascript高级程序设计》当中,写到:“超时调用的代码(setTimeout)都是在全局作用域中执行的,因此函数中的this的值,在非严格模式下是指向window对象,在严格模式下是指向undefined”。

var name = "HELLO";
function Person(){
    this.name = "hello";
    this.showName = function(){
        console.log(this.name);
    }
    setTimeout(this.showName,50);
}
var person = new Person();      //在setTimeout(this.showName,50)语句中,会延时执行this.showName方法,this.showName方法即构造函数Person()里面定义的方法。50ms后,执行this.showName方法,this.showName里面的this此时便指向了window对象,因此输出 HELLO
var name = "HELLO";
function Person(){
    this.name = "hello";
    var that = this;
    this.showName = function(){
        console.log(that.name);
    }
    setTimeout(this.showName,50)
}
var person=new Person();     //在Person函数当中将this赋值给that,即让that保存Person对象,因此在setTimeout(this.showName,50)执行过程当中console.log(that.name)会输出Person对象的属性hello
var name = "HELLO";
var person = {
    name: "hello",
    showName: function(){
        console.log(this.name);
    },
    sayName: function(){
        (function(callback){
            callback();
        })(this.showName)
    }
}
person.sayName();     //匿名函数的执行同样在默认情况下this是指向window的,除非手动改变this的绑定对象,因此输出 HELLO

(6)Eval函数:该函数执行的时候,this绑定到当前作用域的对象上

var name = "HELLO";
var person = {
    name: "hello",
    showName: function(){
        eval("console.log(this.name)");
    }
}
person.showName();     //hello
var a = person.showName;
a();     // HELLO

(7)箭头函数:ES6里面this指向固定化,始终指向外部对象,因为箭头函数没有this,因此它自身不能进行new实例化,同时也不能使用call, apply, bind等方法来改变this的指向

function Timer() {
    this.seconds = 0;
    setInterval( () => this.seconds ++, 1000);
} 
var timer = new Timer();
setTimeout( () => console.log(timer.seconds), 3100);     //构造函数内部的setInterval()内的回调函数,this始终指向实例化的对象,并获取实例化对象的seconds的属性,每1s这个属性的值都会增加1,因此最后输出 3

相关文章

  • JS中this关键字详解

    1、JS中函数的几种调用方式 (1)普通函数调用(2)作为对象方法调用(3)作为构造函数调用(4)apply/ca...

  • JS写事件代理

    js中的事件委托或是事件代理详解

  • js中的this关键字详解.jQuery中事件

    this是Javascript语言的一个关键字它代表函数运行时,自动生成的一个内部对象,只能在函数内部使用,下面分...

  • 前端开发:详细讲解this指向的相关知识

    在前端js中,this虽然只是其中的一个关键字而已,但是确实一个比较特殊的关键字。为什么说this在js关键字中很...

  • c++ volatile关键字

    Ref cppreference - const vs volatileC/C++中volatile关键字详解 v...

  • js 中的变量命名 关键字

    关键字和保留字 关键字 就是在js中已经被使用了的单词。 js本身已经赋予其功能 保留字 在未来js标准中可能被用...

  • js作用域

    title: js作用域详解date: 2019-03-15 09:45:23tags: js 变量作用域 js中...

  • 创建对象

    js中没有类这个概念,与之对应的叫做对象。 new关键字相当于class关键字 js中,类和函数都是使用funct...

  • 简单案例来看JS中的面向对象

    在JS中,一般情况下我们都是直接写函数,直接调用,但是发现JS中也有new关键字,那么new关键字作为创建对象的关...

  • 10个比较流行的JavaScript面试题

    1.如何理解 JS 中的this关键字? JS 初学者总是对this关键字感到困惑,因为与其他现代编程语言相比,J...

网友评论

      本文标题:JS中this关键字详解

      本文链接:https://www.haomeiwen.com/subject/cysuihtx.html