这是 Javascript Prototype 属性的预期行为吗?
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'"
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'"
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
通常,从构造函数返回值不会实现任何目标。看起来,如果返回一个 JavaScript 原语(例如数字或字符串),则使用
new
(var y = new math1();
) 的对象实例化过程将按照您的方式工作期望,忽略这个值。然而,如果您返回一个 JavaScript 对象(例如
{}
),则使用new
的实例化过程似乎不会以相同的方式工作。相反,您的变量 y 加载的是返回的对象,而不是 math1 的新实例。Normally there is nothing to be achieved from returning a value from an constructor. It seems that if a JavaScript primitive such as a number or string are returned, the object instantiation process with
new
(var y = new math1();
) works as you would expect, ignoring this value.However it seems if you return a JavaScript object such as
{}
the instantiation process withnew
doesn't work in the same way. Instead your variable y is loaded with the object returned not with a new instance of math1.