Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript - Custom Prototype - Syntax Error

I am trying to develop a custom prototype in Javascript(please see code below).

This code works fine if I replace the character with $ character. However, I prefer using character over $ character. If I use character I get the below error message:

Uncaught SyntaxError: Invalid or unexpected token

Is there any way or workaround to make the below code work with character?

<!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>

1 Answers

JavaScript allows a wide range of characters in identifiers (details in the spec here). The first character of an identifier is a bit more restricted than the subsequent ones, but still allows a lot of freedom.

The first character must be $, _, or a Unicode character with the "ID_Start" property according to the Unicode standard (spec link). The character ₹ doesn't have ID_Start, so you can't use it as the first character of a JavaScript identifier.

Subsequent characters must be $, _, or a Unicode character with the "ID_Continue" property. FWIW, you couldn't use that character in an identifier at all, because it doesn't have ID_Continue, either.

So why is $ (a dollar sign) allowed when (a Rupee sign) and other currency symbols like £, , ¥, and such are not? Purely because Brendan Eich thought it would be useful to allow $ in identifiers and made an exception for it.

You could use Rs if you liked. Not as good, but...

function Rs() { }
Rs.prototype = ...;
like image 80
T.J. Crowder Avatar answered Jun 07 '26 23:06

T.J. Crowder



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!