为什么(function(){return this})。bind('abc')()==='abc'等于false?

时间:2018-03-02 06:07:37

标签: javascript

假设我有这样的功能:

var f1=function(){
   return this;
};
console.log(f1.bind('abc')()==='abc');

据我所知,f1.bind('abc')应该创建一个返回'abc'的新函数,所以我猜它应该有与

相同的输出
console.log('abc'==='abc')

这是真的,但现在输出是假的,我的猜测有什么问题?

2 个答案:

答案 0 :(得分:4)

f1.bind('abc')返回string,'abc'类型为var f1=function(){ return this; }; console.log(typeof(f1.bind('abc')())); console.log(typeof('abc'));。 所以===给出错误,因为它是将对象与字符串进行比较。

class TenancyDocument(models.Model):
    building = models.ForeignKey(Building, ondelete='CASCADE', null=True, blank=True)
    prop = models.ForeignKey(Property, ondelete='CASCADE', null=True, blank=True)

    def clean(self):
        if not self.building and not self.prop:
            raise ValidationError('Must provide either building or property.')
        if self.building and self.prop:
            raise ValidationError('Select building or property, but not both.')
        super().clean()

答案 1 :(得分:4)

在非严格模式下,原始值包含在 Object 中。因此,'abc'变为new Object('abc')

在严格模式下,这不会发生。

'use strict';

var f1 = function() {
  return this;
};
console.log(f1.bind('abc')() === 'abc');

引用strict mode

的ES6规范
  

如果在严格模式代码中评估this,则this值不会强制转换为对象。此值nullundefined未转换为全局对象,并且原始值不会转换为包装器对象。通过函数调用传递的this值(包括使用Function.prototype.applyFunction.prototype.call进行的调用)不会强制将此值传递给对象(9.2.1.2,19.2.3.1,19.2。 3.3)。