[英]in javascript objects, do “static” functions and prototype functions share same namespace?
regardless of the wisdom of such a naming scheme, is the following valid?不管这种命名方案是否明智,以下是否有效?
var F = function() { this.f1 = function() {} } F.f1 = function() {} // "static" call var v1 = F.f1(); // prototype call var f = new F(); var v2 = f.f1();
it seems it should be ok since, for example, var
and this
variables within an object function do not share the same space.看起来应该没问题,例如,
var
和 object function 中的this
变量不共享相同的空间。
Yes, that is valid.是的,这是有效的。
In your example, F
is a function which you assign a property called f1
which is a function itself.在您的示例中,
F
是 function ,您为其分配了一个名为f1
的属性,该属性本身就是 function 。 If you were to change the code to read f = new F()
, then f
is an object which inherits from F
's prototype, but they're still two distinct objects.如果您将代码更改为
f = new F()
,那么f
是一个 object ,它继承自F
的原型,但它们仍然是两个不同的对象。
It is valid.这是有效的。
Like the others have stated, there are no prototype related issues here.就像其他人所说的那样,这里没有与原型相关的问题。
You are attaching 2 propertyes to 2 different objects:您将 2 个属性附加到 2 个不同的对象:
So, since F !== new F()
, they are 2 different thing with different props.因此,由于
F !== new F()
,它们是具有不同道具的 2 个不同的东西。
If you want to make use of the prototypal inheritance, you can consider the following example:如果要使用原型 inheritance,可以考虑以下示例:
var F = function(){}
// function visible to all of F's instances
F.prototype.f1 = function(){console.log("I'm inherited!");}
// a so called "static" function
F.f1 = function(){console.log("I'm static!");}
var instance1 = new F();
var instance2 = new F();
// function visible only to this instance of F
instance1.f1 = function(){console.log("I'm visible only to this instance of F");}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.