简体   繁体   English

无法在javascript中访问函数的原型方法

[英]Can not access function's prototype's method in javascript

I am going through JS the good parts and come to this example. 我将介绍JS的主要部分,并介绍此示例。 In the last line I attempt to call upon a method that is defined in the prototype chain of the sum function. 在最后一行中,我尝试调用sum函数原型链中定义的方法。 I am confused as to why this does not work. 我对为什么这不起作用感到困惑。

Define the sum function: 定义求和函数:

var sum = function(){
    var i, sum=0;
    for(i=0;i<arguments.length;i+=1){
        sum += arguments[i];
    }
    return sum;
}

add the method method to the function prototype 将方法方法添加到函数原型中

Function.prototype.method = function(name, func){
    this.prototype.name = func;
}

use the method method to add an 'add' method to sum 使用method方法添加一个“ add”方法求和

sum.method('add', function(a,b){
    return a + b;
})

The prototype method is clearly defined but I can not access it via the prototype chain: 原型方法已明确定义,但我无法通过原型链访问它:

sum.prototype.add(5,5); //returns 10
sum.add(5,5); //TypeError: sum.add not defined

In the last line why can I not access the method defined in the prototype chain of the sum function? 在最后一行中,为什么我不能访问sum函数原型链中定义的方法?

sum.prototype has nothing to do with the prototype of the function. sum.prototype与该函数的原型无关。 sum.prototype is the prototype of instances of sum when called as constructor (ie with new ): sum.prototypesum 实例的原型,当作为构造函数调用时(即new ):

var instance = new sum(); // doesn't make sense, I know
Object.getPrototypeOf(instance) === sum.prototype; // true
instance.add // function

The prototype of sum itself can be accessed via Object.getPrototypeOf(sum) and is Function.prototype . sum的原型本身可以通过Object.getPrototypeOf(sum)访问,并且是Function.prototype

Object.getPrototypeOf(sum) === Function.prototype; // true

Btw, that's exactly why sum.method() works: You are extending sum 's prototype by assigning to Function.prototype.method . 顺便说一句,这就是sum.method()起作用的原因:您通过分配给Function.prototype.method来扩展sum的原型。


I'm not sure what you are trying to do, but extending functions via their prototype chain is probably not the right solution to your problem. 我不确定您要做什么,但是通过原型链扩展功能可能不是解决问题的正确方法。

If you want to add a property to sum , then just assign it directly: 如果要向sum添加一个属性,则只需直接分配它:

sum.add = function() { ... };

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM