我注意到从绑定(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)
[...]
- Let F be BoundFunctionCreate(Target, thisArg, args).
[...]
- Return F.
9.4.1.3 BoundFunctionCreate (targetFunction, boundThis, boundArgs)
[...]
- Set the [[Call]] internal method of obj as described in 9.4.1.1.
9.4.1.1
[[Call]]
( thisArgument, argumentsList)[...]
- Return Call(target, boundThis, args).
7.3.12 Call(F, V, [argumentsList])
[...]
- Return F.[[Call]](V, argumentsList).
9.2.1
[[Call]]
( thisArgument, argumentsList)[...]
- Perform OrdinaryCallBindThis(F, calleeContext, thisArgument).
9.2.1.2 OrdinaryCallBindThis ( F, calleeContext, thisArgument )
[...]
- If thisMode is strict, let thisValue be thisArgument.
- 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/