gpt4 book ai didi

Javascript - 自定义原型(prototype) - 语法错误

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:00:23 24 4
gpt4 key购买 nike

我正在尝试用 Javascript 开发自定义原型(prototype)(请参阅下面的代码)。

如果我用 $ 字符替换 字符,此代码可以正常工作。但是,我更喜欢使用 字符而不是 $ 字符。如果我使用 字符,我会收到以下错误消息:

Uncaught SyntaxError: Invalid or unexpected token

是否有任何方法或变通方法可以使以下代码与 字符一起使用?

<!DOCTYPE html>
<html lang="en-IN">
<head>
<meta charset="UTF-8" />
<script>
function ₹(input){
this.input=input;
var customPrototype={};
customPrototype.upper=function(){
return input.toUpperCase();
}
customPrototype.count=function(){
return input.length;
};
customPrototype.lower=function(){
return input.toLowerCase();
}
customPrototype.__proto__ = ₹.prototype;
customPrototype.constructor = ₹;
return customPrototype;
}
₹.prototype = {
top: function() {
return this.upper();
},
size: function() {
return this.count();
},
bottom: function() {
return this.lower();
}
};
</script>
</head>
<body>
<script>
console.log(₹("ProgrAmmeR").top());
console.log(₹("ProgrAmmeR").bottom());
console.log(₹("ProgrAmmeR").size());
</script>
</body>
</html>

最佳答案

JavaScript 允许在标识符中使用各种字符 (details in the spec here)。标识符的第一个字符比后面的字符更受限制,但仍然有很大的自由度。

根据 Unicode 标准 (spec link),第一个字符必须是 $_ 或具有“ID_Start”属性的 Unicode 字符。 The character ₹没有 ID_Start,因此您不能将它用作 JavaScript 标识符的第一个字符。

后续字符必须是$_ 或具有“ID_Continue”属性的Unicode 字符。 FWIW,您根本不能在标识符中使用该字符,因为它也没有 ID_Continue。

那么为什么 $(美元符号)在 (卢比符号)和其他货币符号(如 £¥ 等等不是吗?纯粹是因为 Brendan Eich 认为在标识符中允许使用 $ 会很有用,并为此破例。

如果您愿意,可以使用 Rs。不太好,但是...

function Rs() { }
Rs.prototype = ...;

关于Javascript - 自定义原型(prototype) - 语法错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41034662/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com