【问题标题】:Prevent from type converting of "this" during a call to a function with apply在使用 apply 调用函数期间防止“this”的类型转换
【发布时间】:2010-01-16 22:23:21
【问题描述】:

为忍者服务,

这就是 ecmascript 5 规范。 (第 118 页)在Function.prototype.apply(thisArg, argArray) 部分中说:

注意:thisArg 值作为 this 值不加修改地传递。这是对第 3 版的更改,其中 undefined 或 null thisArg 被替换为全局对象,ToObject 应用于所有其他值,并将结果作为 this 值传递。

这听起来很有希望,但是这个规范还没有在任何现代浏览器中实现,所以我们必须处理第三个规范的实现。

我现在的问题是“如何让typeof 语句变为 TRUE?

var foo = function (arg1, arg2) {
      alert(typeof this == "string");
};

foo.apply("bar", ["arg1", "arg2"]);

有什么想法吗?

【问题讨论】:

    标签: javascript


    【解决方案1】:

    JavaScript 中有两种类型的字符串。

    typeof字符串的那些

    "hello"
    

    还有那些带有 typeof 对象的

    new String("hello");
    

    apply 将始终包装您作为对象传递的任何值,因为您需要通过 this 关键字来使用它。

    【讨论】:

      【解决方案2】:

      使用this instanceof String(仅限同一窗口)或使用Object.prototype.toString.call(this) === "[object String]"(跨窗口工作)。

      【讨论】:

        【解决方案3】:

        目前唯一的一件事就是检查类型

        使用Object.prototype.toString.call(string) == "[object String]"; 并将this 转换回字符串,如:

            var isString = function(string) {
              return Object.prototype.toString.call(string) == "[object String]";
            };
        
            var isNumber = function(number) {
              return Object.prototype.toString.call(number) == "[object Number]";
            };
        
            var toRightType = function(mess) {
              if(isString(mess)) {
                mess = mess+"";
              }
        
              if(isNumber(mess)) {
                mess = mess+0;
              }
        
              return mess;
            };
        
        
            var foo = function () {
              var _this = toRightType(this);
            };
        
            foo.apply("bar");
        

        这是 javascript 中悲伤的章节之一:(

        【讨论】:

          猜你喜欢
          • 2015-04-22
          • 2013-07-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2020-02-07
          • 1970-01-01
          相关资源
          最近更新 更多