LoginSignup
0
0

More than 5 years have passed since last update.

[クイズ]javascriptと仲良くなるための一歩 第32話「apply,call」

Posted at

整理:applyとcall

function f(){ console.log(this.x); }
var obj = { x:1 }

f();          //=> undefined
f.apply(obj); //=> 1
f.call(obj);  //=> 1
var obj = {
           x:1,
           doit: function(){ console.log("Hi! " + this.x); }
          }
var obj2 = { x:2 }

obj.doit();           //=> Hi! 1
obj.doit.apply(obj2); //=> Hi! 2
obj.doit.call(obj2);  //=> Hi! 2

問題「引数の渡し方の違い」

function f(a, b){ console.log("this.x=" + this.x + ", a=" + a + ", b=" + b) }
f(1,2);                //=> this.x=undefined, a=1, b=2
f.apply(?); //=> this.x=10, a=1, b=2
f.call(?);   //=> this.x=10, a=1, b=2

:mouse:
:cow:
:tiger:
:rabbit:
:dragon_face:
:snake:
:horse:
:sheep:
:monkey_face:
:bird:
:dog:
:boar:
:mouse:
:cow:
:tiger:
:rabbit:
:dragon_face:
:snake:
:horse:
:sheep:
:monkey_face:
:bird:
:dog:
:boar:

答え

function f(a, b){ console.log("this.x=" + this.x + ", a=" + a + ", b=" + b) }
f(1,2);                //=> this.x=undefined, a=1, b=2
f.apply({x:10}, [1,2]); //=> this.x=10, a=1, b=2
f.call({x:10}, 1, 2);   //=> this.x=10, a=1, b=2
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0