javascript - 在 String.prototype 中使用 'this'

标签 javascript

<分区>

对于各种 javascript 应用程序,我经常使用我编写的一个名为 isBlank() 的小函数:

isBlank = function(text) {
    while(text[0] == ' ') text = text.substr(1);
    return (text === '');
}

这个函数所做的就是删除输入字符串开头的所有空格,然后返回 true 或 false(如果结果为空或不为空)。所以我尝试将这个函数做成String原型(prototype)如下:

String.prototype.isBlank = function() {
    while(this[0] == ' ') this = this.substr(1);
    return (this === '');       
}

但是,当您尝试以下操作时,原型(prototype)版本会出现“无效的左手分配”错误:

"      ".isBlank();

ReferenceError: Invalid left-hand side in assignment

我想这个问题源于我在 while 循环中重新分配“this”对象这一事实,但由于我仍在学习 java 脚本,我想知道是否有人能够更详细地解释为什么会这样原型(prototype)不起作用。我对这个问题的理论方面更感兴趣,而不是对如何将 isBlank() 函数变成满足我要求的字符串原型(prototype)感兴趣。

谢谢!

最佳答案

您不能重新分配它。这就是错误的意思。

ECMAScript spec .

10.1.7 This

There is a this value associated with every active execution context. The this value depends on the caller and the type of code being executed and is determined when control enters the execution context. The this value associated with an execution context is immutable.

另一个链接 explaining this

关于javascript - 在 String.prototype 中使用 'this',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12694876/

相关文章:

javascript - 如何使用 Javascript/underscorejs 找到包含对象的数组的交集?

javascript - 如何计算两点之间的 Angular ?

javascript - jQuery 不在 AJAX POST 请求上发送 JSON

javascript - 在滚动事件上添加和删除类

javascript - Javascript 中 URL 的 HTTP 状态代码

javascript - 如何使用 JavaScript 截取 div 的屏幕截图?

javascript - Three.js CanvasRenderer,在将图像纹理设置为平面时遇到问题

Javascript OOP - 在异步回调中丢失了它

javascript - Google 表格附加组件,未添加自定义菜单?

javascript - 为什么在使用它之前在 Javascript 中声明一个变量不是必须的?