javascript - 无法访问通过 Prototype 添加到 Javascript 对象的方法

标签 javascript angularjs node.js

我在 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 with Object.getPrototypeOf). The actual prototype of a constructor is Function.prototype since constructors are functions. Its prototype 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/

相关文章:

node.js - Docker 容器中 Apache 反向代理的最小配置

javascript - Node.js https.post 请求

javascript - Angular-UI Bootstrap Datepicker 新日期

javascript - 当字符串用作输入名称时,无法读取未定义的属性 '$pristine'

javascript - 如何在页面刷新后保存动态复选框状态?

javascript - 比较 NodeJS 缓冲区同时避免时序攻击

javascript - Node : Cannot replace Intl to use IntlPolyfill

javascript - 分配给每个点击次数/点击次数的功能

javascript - 从@angular 2.4.9 升级到@angular 4.0.0 @angular/cli 后显示无效错误

javascript - 结合 geojson 和 json 制作传单