I am new to Javascript language, recently I started looking into js prototype and got confused by some odd output in below code:
Array.prototype.print = function() {
console.log(this)
}
[1, 2, 3, 4].print();
Could anyone tell me why it returns
Cannot read property 'print' of undefined'
If I declare var array = [1, 2, 3, 4]
then call print function by array.print()
, it works fine, so I got confused how is that different?
Array.prototype.print = function() {
console.log(this)
}
var array = [1, 2, 3, 4]
array.print()