方法中this和函数中的this

2019-09-30  本文已影响0人  木中木

本文旨在阐述this指针在不同场景中的指向

this一般情况分以下四种:

    1.构造函数中,返回当前创建的对象

`

class Person {

constructor(){

    console.log(this)

}

}

const p = new Person()

Person {}

`

这里一起说明下new操作,new操作符其实做了四个步骤,

    ①创建一个新对象

    ②将当前作用域指向这个心对象,也就是绑定this

    ③初始化构造函数操作

    ④返回一个新对象

可以使用native function来实现

`

function ConstruFunc(name, age) {

    const obj = {};

    obj.__proto__ = Person.prototype;

    obj.name = name;

    obj.age = age;

    return obj;

}

let person2 = ConstruFunc('maclery', 29);

console.log(person2);

输出:

    Person {name:"maclery",age:29}

        age: 29

        name: "maclery"

        __proto__: Object

`

2.作为对象的属性调用——谁调用指向谁

`

const name = 'zhangsan';

const objFunc = {

    name: 'maclery',

    getName: function() {

        return this.name;

    }

}

console.log(objFunc.getName())  // 输出: maclery

如果使用
    const getName = objFunc.getName;

    console.log(getName()) // 输出:zhangsan,此时this指向window,相当于window.getName();这个是下面要说的自由函数

`

3.自由函数调用

var name = 'zhangsan';

function getName() {

    var name = 'maclery';

    console.log(this.name);

}

getName(); // 输出 ‘zhangsan’

这里指向 window,在严格模式中,则是undefined

`

var name = 'zhangsan';

function getName() {

    'use strict'

    var name = 'maclery';

    console.log(this.name);

}

getName(); //直接报错

VM1631:8 Uncaught TypeError: Cannot read property 'name' of undefined

    at getName (<anonymous>:8:22)

    at <anonymous>:12:1

`

这里自由函数调用,还包含定时器调用、函数内嵌套调用,以及对象函数内嵌套函数调用,在未明确说明this时,都是指向window

`

const name = 'linjian';

const obj = {

    name: 'maclery',

    getName: function() {

        function temp() {

            console.log(this.name)

        }

        temp();

        setTimeout(function(){

            console.log(this.name)

        },0);

    }

}

obj.getName()

输出 zhangsan

函数内嵌套:

    const name = 'zhangsan';

    function getName() {

        const name = 'maclery';

        function innerGetName() {
            console.log(this.name);

        }

        innerGetName();

    }

    getName();

    // 输出 ‘张三’

`

4.事件绑定方法——总是指向当前被绑定事件的对象

`

const obj = document.querySelector('#name');

obj.addEventListener('click',function() {
    console.log(this);// 指向 obj

})

`

5.箭头函数

   普通函数的箭头函数是在执行过程中,绑定this,并且总是指向父级this,箭头函数使用apply,call、bind无法改变this指向

`

const name = 'maclery'

const obj = {

    name:'linjian',

    getName: () =>{

        console.log(this.name)

    }

}

obj.getName(); // 输出:maclery

`

    

上一篇 下一篇

猜你喜欢

热点阅读