Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[js] js的函数有哪几种调用形式? #908

Open
haizhilin2013 opened this issue Jul 17, 2019 · 11 comments
Open

[js] js的函数有哪几种调用形式? #908

haizhilin2013 opened this issue Jul 17, 2019 · 11 comments
Labels
js JavaScript

Comments

@haizhilin2013
Copy link
Collaborator

js的函数有哪几种调用形式?

@haizhilin2013 haizhilin2013 added the js JavaScript label Jul 17, 2019
@ghost
Copy link

ghost commented Jul 17, 2019

fn(arg1, arg2, ...)
fn.call(thisArg, arg1, arg2, ...)
fn.apply(thisArg, [arg1, arg2, ...])

其中,callapply 使得函数内的 this 被绑定到 thisArg 上。

同时可以使用 fn.bind(thisArg, ...) 来产生绑定到某个 this 的函数变体。

@NicholasBaiYa
Copy link

直接调用 fn()
自调用 (function())();
做为对象的属性调用 obj.fn()

@shejiJiang
Copy link

new Xxx(),构造函数调用

@chenweihuan
Copy link

function fn(){}

  • 正常的函数调用
    fn()
  • 作为对象方法调用
    let obj = {fn:function(){}};
    obj.fn()
  • 使用构造函数调用
    new fn()
  • 使用call或apply调用
    fn.call() || fn.apply()

@nowherebutup
Copy link

  • 全局调用
  • 对象调用
  • call,apply调用
  • new 构造函数调用

@Kntt
Copy link

Kntt commented Aug 10, 2019

如果是问函数自执行的方式有哪些呢?

// 1
(func (){

})()
//...

@Konata9
Copy link

Konata9 commented Aug 21, 2019

// 1. 全局调用
function fn(args){}
fn(args)

// 2. 作为对象的属性,以及作为构造函数 new 调用
Obj.prototype.fn = function(args){}
const obj = new Obj()
obj.fn(args)

// 3. call/apply/bind
fn1.call(this, arg1,arg2,...)
fn2.apply(this, [arg1, arg2, ...])

fn3 = fn1.bind(this)
fn3(arg1, arg2, ...1)

@zhuyuedlut
Copy link

这道题主要是想考察什么了

@kruzabc
Copy link

kruzabc commented Jan 8, 2020

还有 eval 大法

@songlovena
Copy link

总体来说,有四种:① 函数独立调用,直接使用fn()形式或自调用,这种调用内部函数this指向window; ② 作为对象的方法被调用,如DOM0绑定事件,元素点onclick这种形式,this指向该对象 ③ 构造函数中调用,this指向实例对象 ④ 使用call、apply调用,this指向绑定的对象。

@xiaoqiangz
Copy link

fn()
object.fn()
new fn()
fn.call(object)
(fn(){
}())

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
js JavaScript
Projects
None yet
Development

No branches or pull requests