无法访问通过原型添加到Javascript对象的方法 [英] Can't access to methods that added via Prototype to Javascript object

查看:86
本文介绍了无法访问通过原型添加到Javascript对象的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 Angular.js 模块中包含此对象声明:

i have this object declaration inside an Angular.js module:

    $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 添加到对象的方法?

Why i cant access to methods that i added via Prototype to my object?

推荐答案

您似乎将函数的原型属性与对象的内部原型相混淆.

You seem to be mistaking a function's prototype property with the internal prototype of an object.

这本书口才的Java语言的相关引用:

请务必注意,原型与构造函数的关联方式(通过其 prototype 属性)与对象拥有原型(可以可以使用 Object.getPrototypeOf 进行检索).构造函数的实际原型是 Function.prototype ,因为构造函数是函数.它的 prototype property 将是通过它创建的实例的原型,但不是它的 own 原型.

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.

这在您的代码示例的上下文中意味着什么:

What this means in the context of your code sample:

$scope.test.prototype.push = function(data) {
    return data;
};

在这里,您已经向 $ scope.test 函数的prototype属性添加了一个push函数,该函数将出现在使用此测试函数作为构造函数创建的对象的原型上(和 new 关键字).

Here you've added a push function to the prototype property of the $scope.test function, which will be present on the prototype of objects created by using this test function as a constructor function (with the new keyword).

$ scope.test 仍然是一个空函数,没有 .push()方法,从而导致错误.如果要向每个函数添加一个push方法,则可以使用Function.prototype(请注意,Function是用于创建新函数的构造函数),但是我不确定我们要去哪里与此.

$scope.test, however, remains an empty function, which has no .push() method, resulting in the error. If you want to add a push method to every function, you could use Function.prototype (note that Function is the constructor with which new functions are created), but I'm not sure where are we going with this.

这篇关于无法访问通过原型添加到Javascript对象的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆