我有这个代码:
function user(name) {
console.log(name);
}
user.prototype.test = function() {
return 2 + 2;
};
console.log(user.prototype.test());
var dany = new user("dany");
var david = new user("david");
console.log(dany.prototype.test());
Run Code Online (Sandbox Code Playgroud)
控制台日志:
4
dany
david
Uncaught TypeError: Cannot call method 'test' of undefined
Run Code Online (Sandbox Code Playgroud)
不应该将test()函数分配给user()函数的所有实例(它是对象构造函数)吗?
如果您碰巧对我应该阅读的内容有更好的建议,请更多地了解原型,请继续;)
编辑:
即使使用:
Object.prototype.test = function() {
return 2 + 2;
};
Run Code Online (Sandbox Code Playgroud)
我仍然在控制台中收到该错误.我以为所有对象都会继承原型函数.
| 归档时间: |
|
| 查看次数: |
44 次 |
| 最近记录: |