我在 Angular.js
模块中有这个对象声明:
$scope.test=function(){
};
$scope.test.prototype.push = function(data) {
return data;
};
我这样调用它:
var a = $scope.test.push(1);
console.error(a);
但我收到此错误:
Error: undefined is not a function (evaluating '$scope.test.push(1)')
为什么我无法访问通过 Prototype
添加到对象的方法?
最佳答案
您似乎将函数的原型(prototype)属性误认为是对象的内部原型(prototype)。
书中的相关引用Eloquent Javascript :
It is important to note the distinction between the way a prototype is associated with a constructor (through its
prototype
property) and the way objects have a prototype (which can be retrieved withObject.getPrototypeOf
). The actual prototype of a constructor isFunction.prototype
since constructors are functions. Itsprototype
property will be the prototype of instances created through it but is not its own prototype.
这在代码示例的上下文中意味着什么:
$scope.test.prototype.push = function(data) {
return data;
};
这里,您已将推送函数添加到 $scope.test
函数的原型(prototype)属性中,该函数将出现在使用此测试函数作为构造函数创建的对象的原型(prototype)上(与 new
关键字)。
$scope.test
仍然是一个空函数,它没有 .push()
方法,从而导致错误。如果你想为每个函数添加一个push方法,你可以使用Function.prototype(注意Function是创建新函数的构造函数),但我不确定我们要去哪里有了这个。
关于javascript - 无法访问通过 Prototype 添加到 Javascript 对象的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31169744/