javascript - 为什么从绑定(bind)函数返回的 `this` 不严格等于传递的原始值?

标签 javascript

我注意到从绑定(bind)函数返回的 this 并不严格等于绑定(bind)时传递的原始值。

根据MDN当调用原始函数时 [[BoundThis]] 被传递。

从绑定(bind)函数返回的this是什么?是[[BoundThis]]吗?

const fn = function() { return this }
const strBound = fn.bind('111')
const numBound = fn.bind(111)
const boolBound = fn.bind(true)

console.log(strBound()) // [String: '111']
console.log(strBound() == '111') // true
console.log(strBound() === '111') // false

console.log(numBound()) // [Number: 111]
console.log(numBound() == 111) // true
console.log(numBound() === 111) // false

console.log(boolBound()) // [Boolean: true]
console.log(boolBound() == true) // true
console.log(boolBound() === true) // false

最佳答案

与往常一样,此行为已由 ECMAScript 规范定义。在这种情况下,实际遵循不同的规范需要一段时间,但如果您对细节感兴趣,就来吧。

19.2.3.2 Function.prototype.bind ( thisArg , ...args)

[...]

  1. Let F be BoundFunctionCreate(Target, thisArg, args).

[...]

  1. Return F.

9.4.1.3 BoundFunctionCreate (targetFunction, boundThis, boundArgs)

[...]

  1. Set the [[Call]] internal method of obj as described in 9.4.1.1.

9.4.1.1 [[Call]] ( thisArgument, argumentsList)

[...]

  1. Return Call(target, boundThis, args).

7.3.12 Call(F, V, [argumentsList])

[...]

  1. Return F.[[Call]](V, argumentsList).

9.2.1 [[Call]] ( thisArgument, argumentsList)

[...]

  1. Perform OrdinaryCallBindThis(F, calleeContext, thisArgument).

9.2.1.2 OrdinaryCallBindThis ( F, calleeContext, thisArgument )

[...]

  1. If thisMode is strict, let thisValue be thisArgument.
  2. Else
    • if thisArgument is null or undefined, then
      Let thisValue be calleeRealm.[[globalThis]].
    • Else
      Let thisValue be ToObject(thisArgument).

7.1.13 ToObject ( argument )

[...]

Number: Return a new Number object whose [[NumberData]] internal slot is set to the value of argument. See 20.1 for a description of Number objects.

String: Return a new String object whose [[StringData]] internal slot is set to the value of argument. See 21.1 for a description of String objects.

  • 原始字符串并不严格等于具有相同值的字符串对象。
  • 原始数字并不严格等于具有相同值的数字对象。

关于javascript - 为什么从绑定(bind)函数返回的 `this` 不严格等于传递的原始值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54173201/

相关文章:

JavaScript 文档.域 : Chrome and Firefox return different

javascript - 使用 jQuery 删除某些字段

javascript - 模板内的 Handlebars 模板

javascript - 在 JSX/React 中通过数组映射后,首先选择 <option> 为空

javascript - 在 JavaScript 中 : If Object is a function then how can it be if a function is an instance of an object

javascript - 找不到模块 '@angular-devkit/schematics/tasks'

javascript - Rails ajax 错误 - SyntaxError : Unexpected token C in JSON at position 0

javascript - 如何用javascript检测html开关状态

javascript - 无法在 Laravel 5 中显示 Google map

javascript - 如何更改jquery中的日期格式?