在原型的方法中弄乱这个 [英] Messing with this in prototype's method

查看:35
本文介绍了在原型的方法中弄乱这个的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好的,情况是这样的:

var vowels = ['a', 'i', 'y', 'e', 'o', 'u'];
String.prototype.isVowel = function () {
  return vowels.indexOf(this) !== -1;
};

alert('a'.isVowel());

它会警告 'false' 因为 this 引用的不是 'a' 而是它的原型.为了让它发挥作用,我们需要做一些改变.

It will alert 'false' since this references not 'a' but its prototype. To make it work we need to make a little change.

String.prototype.isVowel = function () {
  return vowels.indexOf(this[0]) !== -1;
};

alert('a'.isVowel());

这将起作用,因为 String.prototype 包含原始字符串的所有字符.这实际上是一种黑客行为,我不喜欢它.

This will work since String.prototype contains all characters of original string. It's a hack actually and I don't like it.

但是我们需要做什么才能使这段代码正常工作?

But what do we need to do to make this code work?

Number.prototype.is5 = function () { return this === 5; }

alert((5).is5()); //will alert 'false'

或者我们只是不需要接触原型?

Or we just don't need to touch prototypes?

推荐答案

问题是所谓的装箱.如果您有一个原始值,然后对该值调用一个方法,它将被包装为 StringNumberBoolean 类型的对象>,或者你有什么.例如,这相当于调用 new String('a').(它记录在 ECMAScript 规范中.)

The problem is what is called boxing. If you have a primitive value and then call a method on that value, it will be wrapped as an object of the type String, Number, Boolean, or what have you. This is equivalent to calling new String('a'), for instance. (It is documented in the ECMAScript specification.)

new String('a')'a' 不同.因此在数组中找不到它.

new String('a') is not the same as 'a'. It therefore is not found in the array.

因此,您需要做的是将值转换回原始值.您始终可以使用 valueOf 方法完成此操作:

What you need to do, therefore, is convert the value back into the primitive value. You can always accomplish this with the valueOf method:

return vowels.indexOf(this.valueOf()) !== -1;

你的方法是调用this[0].这是有效的,因为它从字符串中获取第一个字符作为原始字符,然后在字符串中找到它.缺点是 ab 也会被这种方法视为元音.

Your method is to call this[0]. This works, because it gets the first character from the string as a primitive, which is then found in the string. The downside is that ab would also be considered a vowel by this method.

与数字类似:

 Number.prototype.is5 = function () { return this.valueOf() === 5; };

<小时>

另外一点:这是 Javascript 的默认行为.正如您所展示的,它并不明显或直观.在 ECMAScript 5 中,创建了严格模式",所有类型的不良行为都被禁用.自动装箱就是其中之一.因此,如果您使用现代浏览器,这将具有预期的行为:


One other point: this is the default behaviour of Javascript. It is not obvious or intuitive, as you have shown. In ECMAScript 5, "strict mode" was created, where all kinds of undesirable behaviours are disabled. Auto-boxing is one of them. So, if you use a modern browser, this will have the expected behaviour:

Number.prototype.is5 = function () {
    "use strict";
    return this === 5;
};

这篇关于在原型的方法中弄乱这个的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆