thisについてです
コピー時のthisの挙動
オブジェクトのメソッドとして実行される場合
‘this’ => 呼び出し元のオブジェクト
関数として実行される場合
‘this’ => グローバルオブジェクト
window.name = 'john';
const person = {
name: 'Tom',
hello: function() {
console.log('Hello ' + this.name); // hello Tom この時オブジェクトのメソッドとして実行されるため person参照
a(); // hello john
}
}
const ref = person.hello;
ref(); // Hello , windowオブジェクトありの時は Hello johnとなる。
/*--
オブジェクトのメソッドとして実行される場合 'this' => 呼び出し元のオブジェクト
関数として実行される場合 'this' => グローバルオブジェクト
--*/
person.hello();
function a(){
console.log('Hello ' + this.name); //この時のthisはグローバル参照
}
コールバック関数のthis
window.name = 'John';
const person = {
name: 'Tom',
hello: function() {
console.log('Hello ' + this.name); //hello Tom
}
}
person.hello();
function fn(ref){
ref(); //関数を実行になるので、window参照のhello johnになる
}
fn(person.hello); //hello John
bind thisを固定した上で呼び出す方法
bind によって’this’や引数を固定した新しい関数を作成 (コピーじゃなくて作成するよ)
bindによるthisの束縛
window.name = 'John';
const person = {
name: 'Tom',
hello: function() {
console.log('Hello ' + this.name);
}
}
person.hello();
const helloTom = person.hello.bind(person); hello関数をpersonと結びつけた関数helloTomを作成
function fn(ref) {
ref();
}
fn(helloTom); //hello Tom
function a (){
console.log('hello'+ this.name);
}
const b = a.bind({name:'Tim'}); a関数をnameをTimに結びつけた関数bを作成
b(); //hello Tim
function c (name){
console.log('hello'+ name);
}
const d = c.bind(null,'Tim'); 第一引数にはthisを、第二引数以降には、引数を入れることができる
c('john'); //hello Tim bindの方が優先される
call,apply
bind
‘this’や引数の参照先を変更
使用時点で実行はしない
call,apply
使用時点で実行
call は 値を使う
applyは配列を使う
call は 値を使う
applyは配列を使う
function a(name) {
console.log('hello ' + name + name1);
}
const tim = {name:'tim'};
const b = a.bind(tim);
b();
a.call(tim,'Tim','bob'); //hello timbob bindと同じで第二関数以下には、関数の仮引数を使える
a.apply(tim,['tim','bob']); //hello timbob 実行まで行われる applyの場合は配列で渡す。 bindと同じで第二関数以下には、関数の仮引数を使える
const array = [1,2,3,4,5];
// const result = Math.max.apply(null,array); //5 この時第一引数thisは不必要 null
const result = Math.max(...array); //5 配列を展開して引数として出力
console.log(result);