Skip to content

关于 this 的解释 #279

Closed
Closed
@bigcake008

Description

@bigcake008

https://github.com/wangdoc/javascript-tutorial/blob/master/docs/oop/this.md

代码:

var o = new Object();

o.f = function () {
console.log(this === o);
}

var f = function (){
o.f.apply(o);
// 或者 o.f.call(o);
};

// jQuery 的写法
$('#button').on('click', f);

在函数 f 中调用 o.f.apply(o) 使得 this 获得正确指向,其中 apply 并不是必要的,也就是说可以直接调用 o.f() 即可获得正确指向。其原因是在函数 f 中调用实例 o 的方法 f ,其上下文已经指向实例 o

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