使用Function.prototype.bind

时间:2018-12-21 11:16:32

标签: javascript

https://tc39.github.io/ecma262/#sec-function.prototype.bind

当我阅读“ NOTE 1 NOTE 2”时,我听不懂吗?

  • 注释1

使用Function.prototype.bind创建的功能对象是奇异对象。它们也没有原型属性。

  • 注释2

如果Target是箭头函数或绑定函数,则随后的F调用将不使用传递给此方法的thisArg。

有人可以举一些例子吗?

2 个答案:

答案 0 :(得分:3)

关于注释1:

const bound = (function(){}).bind();
console.log(bound instanceof Function);
console.log(!("prototype" in bound));
// being an "exotic object" just means that it behaves unusual - in this case,
// having a special [[call]] operation

关于注释2:

function example() { "use strict"; console.log(this); }
const bound = example.bind("Hello");
const boundAgain = bound.bind("World");
console.log(bound(), boundAgain()); // Hello Hello

function makeArrow() { "use strict"; return () => console.log(this); }
const arrow = makeArrow.call("Hello");
const boundArrow = bound.bind("World");
console.log(arrow(), boundArrow()); // Hello Hello

答案 1 :(得分:1)

注1:绑定函数没有原型

const target = { foo: "bar" };
const f = function() {};
const bound = f.bind(target);
console.log("f.prototype", f.prototype);
console.log("bound.prototype", bound.prototype);

VM439:4 f.prototype {constructor: ƒ}
VM439:5 bound.prototype undefined

注2:箭头功能无法绑定

const target = { foo: "bar", toString: function() { return "foobar"; } };
const normal = function() { return this; };
const arrow = () => { return this; };
const boundNormal = normal.bind(target);
const boundArrow = arrow.bind(target);
console.log("normal()", normal());
console.log("boundNormal()", boundNormal());
console.log("arrow()", arrow());
console.log("boundArrow()", boundArrow());
console.log("normal.call(target)", normal.call(target));
console.log("arrow.call(target)", arrow.call(target));

normal() Window {postMessage: ƒ, blur: ƒ, focus: ƒ, close: ƒ, parent: Window, …}
boundNormal() {foo: "bar", toString: ƒ}
arrow() Window {postMessage: ƒ, blur: ƒ, focus: ƒ, close: ƒ, parent: Window, …}
boundArrow() Window {postMessage: ƒ, blur: ƒ, focus: ƒ, close: ƒ, parent: Window, …}
normal.call(target) {foo: "bar", toString: ƒ}
arrow.call(target) Window {postMessage: ƒ, blur: ƒ, focus: ƒ, close: ƒ, parent: Window, …}