Reputation: 9066
a wrote a random code which adds method to a primitive data type.it supposed to add 10 to the desired number.i was not sure if it's gonna work.i wrote this+10
.but it returned 15 which was correct.i suppose THIS keyword refers to the object itself.But here it seems it refers to the value of the number variable.i mean should it not be something like this.value+10
; i am confused..any reasonable explanation for this!!??
<html>
<body>
<script>
function add(){
console.log(this+10);
}
var number=5;
Number.prototype.add=add;
number.add();
</script>
</body>
</html>
Upvotes: 0
Views: 54
Reputation: 1887
Please find some details inside comment tags.
<html>
<body>
<script>
function add(){
console.log(this+10);
}
/*
Here you created a Number primitive type
->console.log(number.__proto__) -> returns: Number{}
*/
var number=5;
/*
This line adds a new method to the Number.prototype object
->console.log(number.__proto__) -> returns Number{add: function}
*/
Number.prototype.add=add;
/*
'this' inside the add method points to 'number'
and because you are trying to do an addition javascript will first try to
find the primitive value for 'this' object calling: valueOf method.
this.valueOf() -> number.valueOf() -> 5
So what is really happens is this:
this + 10 -> number.valueOf() + 10 -> 5 + 10 -> 15
*/
number.add();
</script>
</body>
</html>
Hope this helps.
Upvotes: 1
Reputation: 781716
When you call a function in the form:
<some expression>.method(arguments)
the value of this
inside the method will be the value of <some expression>
. This is called the context in Javascript.
If the expression is just a variable, then the value of this
will be the value of that variable.
Upvotes: 3