简体   繁体   English

如何在JavaScript的全局范围内向内部函数原型添加函数?

[英]How to add functions to prototype of inner function in the global scope in JavaScript?

function A() {  
    this.B = function() {  
        var bla;
    };
}
A.B.prototype.foo = function() {console.log("Do whatever");};

I get this: 我明白了:

TypeError: Cannot read property 'prototype' of undefined TypeError:无法读取未定义的属性“prototype”

How to add a function to the prototype of B in this case? 在这种情况下如何向B的原型添加函数?

There are a couple of mistakes in our code... here is how: 我们的代码中有几个错误...这是如何:

function A() {
   this.B = function() {
      var blah;
   };
}

a = new A();
a.B.prototype.foo = function()  {console.log("Do whatever")};

Your first issue was doing: 你的第一个问题是:

this.B() = function...

That's not valid code, since you were calling method B and assing it a function, you had to reference the attribute. 这不是有效的代码,因为你正在调用方法B并为它提供一个函数,你必须引用该属性。

Your other mistake, was not instantiating an "A" object, the function by itself can't be used as an object, it can only be called. 你的另一个错误,就是没有实例化一个“A”对象,这个函数本身不能用作对象,它只能被调用。 That's why when you had: 这就是为什么当你有:

A.B.prototype

You recieved that error message. 您收到了该错误消息。

I hope that clears things up a bit for you, let me know if you have more doubts. 我希望能为你解决一些问题,如果你有更多疑问,请告诉我。

You need to make the inner function accessible by adding it to the outer prototype, then you can add functions to the inner object by using Outer.prototype.Inner.prototype without the immediate need for an instance of the outer object. 您需要通过将内部函数添加到外部原型来使其可访问,然后您可以使用Outer.prototype.Inner.prototype将函数添加到内部对象,而不需要外部对象的实例。

function A() {this.a="a";}
A.prototype.B = function() {this.b="b";}
A.prototype.B.prototype.foo = function() {console.log("b is:"+this.b);}
var a=new A();
var b=new a.B();
b.foo();

B is a property of A , and can only be accessed from instances of A . BA的属性,只能从A实例访问。

var aObj = new A;
aObj.B();

You cannot access AB without using an instance of A . 如果不使用A实例,则无法访问AB

You could access aObj.B.prototype , and add methods to that. 您可以访问aObj.B.prototype ,并aObj.B.prototype添加方法。

aObj.B.prototype.foo = function(){
    return 'test';
};
var bar = new aObj.B;
console.log(bar.foo()); // 'test'

var bObj = new A;
var foobar = new bObj.B;
console.log(foobar.foo()); // `foo` is undefined

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

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