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

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

  •  
  •   xxxpara · Apr 25, 2015 · 4022 views
    This topic created in 4046 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
        1
    liangdi  
       Apr 25, 2015 via iPhone
    类似其他面向对象语言的静态变量?
    function func(){
    this.member=123;
    }
    func.static_member=456

    ...

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