Skip to content
Advertisement

Different output from prototype function and normal function

I’m trying figure out what’s the difference between prototype function and normal function

here’s my example: Task is to create function in ‘OOP way’ that will check if string is Uppercased.

Why im getting different output?

String.prototype.isUpperCase = function () {
    return this === this.toUpperCase();
}

function check(str) {
    return str === str.toUpperCase();
}

let str = 'C';


console.log(str.isUpperCase())
console.log(check(str))

Advertisement

Answer

this.toString() will do the trick for you.

"" and new String("") are different. The this inside the prototype function is an instance of the String class.

String.prototype.isUpperCase = function () {
    return this.toString() === this.toUpperCase();
}

function check(str) {
    return str === str.toUpperCase();
}

let str = 'C';


console.log(str.isUpperCase())
console.log(check(str))
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement