Is this the expected behavior of a Javascript prototype property?

function math() { return 'x' } math.prototype.sqrt = function(a){return Math.sqrt(a)} var x = new math(); x.sqrt(9); //gives 3 function math1() { return {} } math1.prototype.sqrt = function(a){return Math.sqrt(a)} var y = new math1(); y.sqrt(9); //throws javascript error "TypeError: Object #<Object> has no method 'sqrt'" 
+4
source share
1 answer

As a rule, nothing can be achieved from returning a value from the constructor. It seems that if a JavaScript primitive, such as a number or a string, returns, the process of creating an object using new ( var y = new math1(); ) works as you would expect, ignoring this value.

However, if you return a JavaScript object, such as {} , the process of creating an instance using new does not work that way. Instead, your y variable is loaded with an object returned not from a new instance of math1.

+4
source

Source: https://habr.com/ru/post/1346354/


All Articles