饥人谷技术博客

call,apply,bind用法

2018-06-29  本文已影响3人  饥人谷_黄洪涛

title: call,apply,bind用法
date: 2018-05-28 23:00:00
tags: call apply bind
categories: 前端


call

var obj = {
   name: 'hht',
   age : 1
}

function f(name,age){
  this.name = name;
  this.age = age;
  console.log(this.name);
  console.log(this.age);
}

f.call(obj,'mmd',18);
image

apply

var obj = {
   name: 'hht',
   age : 1
}

function f(name,age){
  this.name = name;
  this.age = age;
  console.log(this.name);
  console.log(this.age);
}

f.apply(obj,['mmd',18]);
f.apply(obj,{0: 'mmd', 1: 18, length: 2});
image

bind

var obj = {
   name: 'hht',
   age : 1
}

function f(){
  for(let i = 0; i < 4; i++)
  {
    console.log(arguments[i]);
  }
  console.log(this);
}

var f1Bind = f.bind(obj,'hht',18);
f1Bind();
f1Bind(1,2);
image
上一篇 下一篇

猜你喜欢

热点阅读