Skip to content

apply、call、bind 一定会改变函数执行时的 this 值吗?(上) #28

@shiiiiiiji

Description

@shiiiiiiji

apply、call、bind 一定会改变函数执行时的 this 值吗?(上)

首先,标题就起的有点不太严谨,我们都知道,this对于函数来说是有多么重要,但this本质上是什么呢?我理解的 this 是函数的一个内部属性值,我们都知道 js 是词法作用域(意思就是代码写好之后,变量值就确定了),但是this却很特殊,他是运行时绑定的(也称“晚绑定”),和函数的运行环境有很大关系。

虽然,上面这些话说的都很模棱两可,但是在业务开发中倒是也没那么重要,是在搞不清楚this的值,或者担心运行时this值不是期望值,可以使用applycallbind绑定函数的this值,具体原理相信大家都理解,或者都接触过。

但是,今天的一段代码,却让我有点百思不得其解,不啰嗦,直接上代码:

// b.js
exports.fn = () =>{
    console.log(this);
}

// a.js
import React from 'react';
import ReactDOM from 'react-dom';
import B from './b.js';
export default class A extends React.Component{
    constructor(props){
        super(props);
    }
    componentDidMount(){
        B.fn.call(this);
    }
    render(
        return(<section>demo</section>);
    )
}

React.render(<A />, document.getElementById('J_reactApp'));

发现,始终无法改变函数 fn 运行时的this值(为 undefined,而不是 A),百思不得其解。

最终,换了种写法,将b.js改造如下:

// b.js
function fn(){
    console.log(this);
}

export default {
    fn
}

便正常了。

但其实,我现在还不是很能明白这里面究竟为何,应该是和“js 模块化”有关系,不过先记在这里,等弄明白了,再写下篇。

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions