gpt4 book ai didi

javascript - 是否有调用所有同名实例方法的静态方法的名称/术语?

转载 作者:行者123 更新时间:2023-11-30 17:21:59 29 4
gpt4 key购买 nike

给定以下代码,是否存在一个静态方法的名称/术语,它为每个现有实例调用同名的实例方法?

这是任何编程语言的常见做法吗?

用例是能够进行一个函数调用并确保所有实例都受到影响,而无需为该方法复制代码。

注意:这只是说明问题的示例代码

window.MyClass = (function(){

var _instances = [];

function MyClass( name ){
_instances.push( this );
this.name = name;
}

MyClass.prototype.myMethod = function( arg ) {
console.log( this );
console.log( arg );
};

// This public static method calls the instance method of the same name for each instance
MyClass.myMethod = function(){
var i = _instances.length;
while( i-- ){
var instance = _instances[i];
instance.myMethod.apply( instance, arguments );
}
};

return MyClass;

})();

a = new MyClass('a');
b = new MyClass('b');

MyClass.myMethod( true );

console.log('--------------------------------------------------------------------------------');

a.myMethod(false);
b.myMethod(false);

http://jsfiddle.net/bryandowning/7sr87/

最佳答案

...is there a name/term for a static method that calls an instance method of the same name for each existing instance?

不,尽管它与发布/订阅有一些相似之处。

如果您跟踪在除弱映射之外的任何实例中创建的每个实例(并且 JavaScript 没有这些 - 但 [参见 draft ES6 spec 撰写本文时的第 23.3.1 节]),您确保这些实例是可达,因此它们不能被垃圾收集清除。这并不理想。

在可行的情况下,更好的方法是让所有实例都引用一个共享的底层单例对象,该对象由“静态”方法更新。它们都将通过它们的共享引用看到更改,但它们不会因对其实例的不必要引用而保留在内存中。 (示例如下。)

如果在调用“静态”方法时他们采取操作很重要,那么更常见的模式是让他们观察共享项目的变化,并让该项目引发改变事件。 (例如,发布/订阅。)实际上,这与您的 _instances 数组相同(因为发布者必须知道要调用哪些订阅者),这只是一种更常见的方法。因此,在那种情况下(需要采取行动),“pub/sub”或“事件订阅者”或“接收器/源”或类似术语可能是相关术语。


共享数据对象的例子:

window.MyClass = (function(){

var shared = {};

function MyClass( name ){
this.name = name;
}

MyClass.prototype.myMethod = function() {
console.log(this);
console.log(shared.arg);
};

// This public static method calls the instance method of the same name for each instance
MyClass.myMethod = function(arg){
shared.arg = arg;
console.log("set shared.arg = " + shared.arg);
};

return MyClass;

})();

a = new MyClass('a');
b = new MyClass('b');

MyClass.myMethod( true );

console.log('--------------------------------------------------------------------------------');

a.myMethod(false);
b.myMethod(false);

关于javascript - 是否有调用所有同名实例方法的静态方法的名称/术语?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24986572/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com