当前位置

网站首页> 程序设计 > 开源项目 > 程序开发 > 浏览文章

apply、call、bind - 小土豆

作者:小梦 来源: 网络 时间: 2024-03-24 阅读:

在Javascript中,Function是一种对象。Function对象中的this指向决定于函数被调用的方式。
这是我们就需要用到这三个小家伙了:call、apply、bind来改变this的指向。

先来谈谈我们所熟知的call和apply

function add(c, d){    return this.a + this.b + c + d;}var o = {a:1, b:2};add.call(o, 3, 4); // 10add.apply(o, [5, 6]); // 14

需要注意的是,如果传入的第一个参数不是对象类型的,那么这个参数会被自动转化为对象类型,例如:

function age() {         console.log(        Object.prototype.toString.call(this)    );}bar.call(7); // [object Number]

接下来说一下bind

ECMAScript 5引入了Function.prototype.bind。调用f.bind(someObject)会产生一个新的函数对象。在这个新的函数对象中,this被永久绑定到了bind的第一个参数上面,无论后期这个新的函数被如何使用。

function f(){    return this.a;}var g = f.bind({a:"jack"});console.log(g()); // jackvar o = {a:37, f:f, g:g};console.log(o.f(), o.g()); // 37, jackfunction Person(name){ this.nickname = name; this.distractedGreeting = function() {    setTimeout(function(){     console.log("Hello, my name is " + this.nickname);   }, 500); }} var alice = new Person('Alice');alice.distractedGreeting();//Hello, my name is undefinedfunction Person(name){  this.nickname = name;  this.distractedGreeting = function() {    setTimeout(function(){      console.log("Hello, my name is " + this.nickname);    }.bind(this), 500); // <-- this line!  }} var alice = new Person('Alice');alice.distractedGreeting();// after 500ms logs "Hello, my name is Alice"this.x = 9; var module = {  x: 81,  getX: function() { return this.x; }}; module.getX(); // 81 var getX = module.getX;getX(); // 9, 因为在这个例子中,"this"指向全局对象 // 创建一个'this'绑定到module的函数var boundGetX = getX.bind(module);boundGetX(); // 81

另外,如果第一个参数为null或者undefined的话,那么,实际上绑定到的是全局对象,即global。这一点对三者都适用。

function age() {         console.log(        Object.prototype.toString.call(this)    );}bar.bind()(); // [object global]bar.apply();  // [object global]bar.call();   // [object global]

热点阅读

网友最爱