Javascript 不工作对象。创建(错误。原型)
我有密码:Javascript 不工作对象。创建(错误。原型),javascript,jquery,prototype,frontend,Javascript,Jquery,Prototype,Frontend,我有密码: var TestError = function () { var that = Error.call(this); return that; }; TestError.prototype = Object.create(Error.prototype); TestError.prototype.why = function(){alert("NOT WORKING")} var err = new TestError(); err.why();//not working :( T
var TestError = function () {
var that = Error.call(this);
return that;
};
TestError.prototype = Object.create(Error.prototype);
TestError.prototype.why = function(){alert("NOT WORKING")}
var err = new TestError();
err.why();//not working :( TypeError: err.why is not a function
但不起作用:(
当我写作时
var TestError = function () {
var that = Error.call(this);
return that;
};
TestError.prototype = Error.prototype;
TestError.prototype.why = function(){alert("WORKING")}
var err = new TestError();
err.why();// working :(
为什么我不能使用Object.create(Error.prototype)?问题不在于
Object.create
。问题在于从构造函数返回它;
这是错误的一个实例,而不是测试错误的一个实例。因此,当您正确地将为什么添加到测试错误中。prototype
时,只有测试错误的实例才会使用该方法,而不是错误
这大致就是第一个示例中的环境状态:
+--------------------+ +------------------------+ +-----------------+
| TestError | | TestError.prototype | +----->| Error.prototype |
+------------+-------+ +-------------+----------+ | +-----------------+
| prototype | *---+------>| why |<Function>| | ^
+------------+-------+ +-------------+----------+ | |
|[[Prototype]]| *---+-+ |
+-------------+----------+ |
|
|
+------------------------+ |
+--------------------+ | <Object> | |
| err |------>+-------------+----------+ |
+--------------------+ |[[Prototype]]| *----+-----------------+
+-------------+----------+
但是,为什么我在TestError.prototype对象中有两个属性。一个是我的自定义属性和“stock”属性。自定义属性我知道为什么有,但我不知道为什么在TestError.prototype中有stock属性。你能告诉我吗?每个对象都有一个内部[[prototype]]
属性,它指向对象的原型。我知道。但是当我运行console.log(TestError.prototype)时,我得到了属性“stock”。为什么?你是说你实际上有一个属性stock
?我不知道它从何而来。run console.log(TestError.prototype).这样做时,您将看到库存在Tester.prototype中。为什么?