在 js 里有办法让对象新建的两个不同实例互相访问吗

2015-04-25 06:43:01 +08:00
 xxxpara

比如var g1=new func();
var g2=new func();
我需要当g1/g2里的某个方法调用时,同时改变g1 g2里的某个成员

3057 次点击
所在节点    JavaScript
11 条回复
liangdi
2015-04-25 07:43:45 +08:00
类似其他面向对象语言的静态变量?
function func(){
this.member=123;
}
func.static_member=456

...

如果不是上面的需求那就直接把对象作为参数传递进去改变值了
oott123
2015-04-25 08:39:14 +08:00
我想可能需要用 g1.prototype.foobar
lxrmido
2015-04-25 09:13:46 +08:00
func.prototype.foobar
babyname
2015-04-25 09:29:16 +08:00
只要出现奇葩的需求,就是代码逻辑有问题。
Dn9x
2015-04-25 09:38:56 +08:00
g1提供set某个成员的方法,g2也提供,再调用你说的那个方法的时候同时调用g1和g2的set方法,
arron
2015-04-25 09:55:03 +08:00
function g(){
}

function g1(){
}

function g2(){
}

g1.prototype = g.prototype;
g2.prototype = g.prototype;

g.prototype.number = 1;
var n1 = new g1(), n2 = new g2();

console.log(n1.number, n2.number); //=> 1
g.prototype.number = 2; //注意不能用 n1.number = 2 或者 n2.number = 2
console.log(n1.number, n2.number); //=> 2
coolzjy
2015-04-25 10:03:00 +08:00
func.prototype.foobar +1
funnyecho
2015-04-25 10:09:37 +08:00
@babyname +1 ~~~
iyangyuan
2015-04-25 10:53:26 +08:00
闭包
Dn9x
2015-04-25 11:02:35 +08:00
prototype的方式这个变量就变成公用的对g1和g2而言,
hanan321
2015-04-25 22:37:37 +08:00
var Class = function () {
var instances = [];
function Class (name) {
this.name = name;
instances.push(this);
}
Class.prototype.setName = function (name) {
instances.forEach(function (instance) {
instance.name = name;
})
}
return Class;
}();

var instance1 = new Class('xx');
var instance2 = new Class('oo');

console.log(instance1.name); // xx
console.log(instance2.name); // oo

instance1.setName('xxoo');

console.log(instance1.name); // xxoo
console.log(instance2.name); // xoo

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/186170

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX