推荐关注
› Meteor
› JSLint - a JavaScript code quality tool
› jsFiddle
› D3.js
› WebStorm
推荐书目
› JavaScript 权威指南第 5 版
› Closure: The Definitive Guide
xxxpara

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

  •  
  •   xxxpara · Apr 25, 2015 · 4516 views
    This topic created in 4212 days ago, the information mentioned may be changed or developed.

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

    11 replies  •  2015-04-25 22:37:37 +08:00
    liangdi
    liangdi
    Apr 25, 2015 via iPhone
    1
    类似其他面向对象语言的静态变量?
    function func(){
    this.member=123;
    }
    func.static_member=456

    ...

    如果不是上面的需求那就直接把对象作为参数传递进去改变值了
    oott123
    oott123
    Apr 25, 2015 via Android
    2
    我想可能需要用 g1.prototype.foobar
    lxrmido
    lxrmido
    Apr 25, 2015
    3
    func.prototype.foobar
    babyname
    babyname
    Apr 25, 2015
    4
    只要出现奇葩的需求,就是代码逻辑有问题。
    Dn9x
    Dn9x
    Apr 25, 2015
    5
    g1提供set某个成员的方法,g2也提供,再调用你说的那个方法的时候同时调用g1和g2的set方法,
    arron
    arron
    Apr 25, 2015
    6
    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
    coolzjy
    Apr 25, 2015
    7
    func.prototype.foobar +1
    funnyecho
    funnyecho
    Apr 25, 2015
    8
    @babyname +1 ~~~
    iyangyuan
    iyangyuan
    Apr 25, 2015 via iPhone
    9
    闭包
    Dn9x
    Dn9x
    Apr 25, 2015
    10
    prototype的方式这个变量就变成公用的对g1和g2而言,
    hanan321
    hanan321
    Apr 25, 2015
    11
    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
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   1310 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 49ms · UTC 19:21 · PVG 03:21 · LAX 11:21 · JFK 14:21
    ♥ Do have faith in what you're doing.