原型JavaScript - 使用构造函数的函数

Dan*_* P. 2 javascript

我有这个代码:

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)

我仍然在控制台中收到该错误.我以为所有对象都会继承原型函数.

Hen*_*son 5

您可以将原型函数和值视为所有实例的默认值.为什么你看到的TypeError是因为你试图调用dany原型和方法test().

试试吧dany.test().

在阅读它的工作原理时,这将是您最好的选择.

TLDR;

你得到的是TypeError因为user函数的实例没有自己的原型.但是,您可以通过__proto__快捷方式访问实例原型.