【问题标题】:How to 'bind' in Javascript without changing the context of 'this'?如何在 Javascript 中“绑定”而不改变“this”的上下文?
【发布时间】:2016-12-31 10:15:54
【问题描述】:

我有一个构造函数和一个闭包。

我的构造函数:

var Item = function(data) {
  this.sayThis = function() {
    console.log(this);
  };
  this.data = data;
};

我的闭包函数:

var $item = function(document, window, ..., itemData) {
  return new Item(itemData);
}.bind(dontWannaPutAnythingHere, document, window, .../*except itemData*/);

如果我在 'thisArg' 中使用任何东西,则新形成的对象内的 'this' 的上下文往往是给定的。我不希望这样,但我仍然想绑定那些文档、窗口和东西,以便我可以在其他时间提供最后一个参数项数据。

我要调用一个新函数为

// Calling it normally.
var someItem = $item("chocolate");
// This should result in Item {data: "chocolate", ...}
// and not anything else.
var someItem = $item("chocolate").sayThis();

干杯, Rj

【问题讨论】:

  • 你要找的词是“部分申请”。
  • 实际上,您调用bind 的函数只执行return new Item(itemData); 而根本不使用this,因此与thisArgument 传递的内容无关。只需使用null
  • 非常感谢伯吉。是的,我打算使用这个闭包来创建类似 jQuery 的对象,这些对象可以具有存在于隔离环境中的变量。 -干杯,Rj

标签: javascript constructor closures this


【解决方案1】:

这似乎有效:

 var Item = function(data) {
  this.sayThis = function() {
    console.log(this);
  };
  this.data = data;
};

var $item = function(document, window, itemData) {
  return new Item(itemData);
}.bind(null, document, window);

// Calling it normally.
var someItem = $item("chocolate");
// This should result in Item {data: "chocolate", ...}
// and not anything else.
var someItem = $item("chocolate").sayThis();

它符合您的要求吗?

JSFIDDLE:https://jsfiddle.net/sfcakq2j/4/

【讨论】:

  • 是的,很抱歉为这么一件小事打扰。感谢战利品!!虽然赛博。祝你有美好的一天,新年快乐。 TC
  • 我会使用undefined,因为它是默认的空值。此外,当没有明显的返回值时,最后一条语句sayThis(和其他方法)应该有一个return this作为最后一条语句,以便对象可以像最后一条语句一样链接方法。
  • 当心,如果你'use strict',这不起作用;那么这将是null
【解决方案2】:

如果您在代码中使用'use strict' 模式,bind(null, ...) 将不起作用。为什么不使用 而不是bind

var $item = (function(document, window){
    return itemData => new Item(itemData);
})(document, window);

【讨论】:

  • 当然绑定到null 确实有效,为什么不呢?!请注意,IEFE 所做的事情与 bind 非常不同。
  • #Thomas 如果您现在不使用 IIFE,您可以稍后传递一个参数吗?我个人认为是不可能的。由于 IIFE 只是正确执行,所以它对我没有用。不过,我对“严格”模式一无所知。我将在严格模式下尝试并确认 - 干杯,Rj
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-11-30
  • 2020-10-25
  • 2010-11-06
  • 1970-01-01
  • 1970-01-01
  • 2017-12-24
  • 2018-06-03
相关资源
最近更新 更多