【问题标题】:JavaScript Array Initialisation in Simple JavaScript Inheritance简单 JavaScript 继承中的 JavaScript 数组初始化
【发布时间】:2010-01-26 02:25:28
【问题描述】:

我目前正在编写一些基于 John Resig -Simple JavaScript Inheritance 的代码。 而且我在初始化数组时遇到了一些麻烦。如果我将数组作为对象的属性并且在调用 init() 期间不初始化数组,则对数组所做的所有修改(如 push、unshift 等)都会影响对象的进一步创建。 我不知道我是否足够清楚,这里有一个例子:

<html>
  <head>
    <script type="text/javascript">
    /*
    insert all the John Resig code here
     */

    var Person = Class.extend({
      arrayTest:[],

      init: function(){
      },
      arrayModif: function(){
        this.arrayTest.push(4);
 this.arrayTest.push(2);
      }
    });

    function example(){
      var a=new Person();
      document.write("This is a before any modifications:"+a.arrayTest+"<br/>");
      a.arrayModif();
      document.write("This is a after modifications:"+a.arrayTest+"<br/>");
      var b=new Person();
      document.write("This is b after creation:"+b.arrayTest+"<br/>");
    };
   </script>
  </head>
  <body onload="example();">
  </body>
 </html>

它将有以下输出:

This is a before any modifications:
This is a after modifications:4,2
This is b after creation:4,2

我想知道是否有人知道如何修改 John Resig 代码以实现以下输出,而不在 init() 中添加任何内容:

This is a before any modifications:
This is a after modifications:4,2
This is b after creation:

谢谢。

【问题讨论】:

    标签: javascript arrays


    【解决方案1】:

    我使用了一个小的附加功能来检查类中的数组(而不是该类的子对象!),并在初始化时复制这些数组以获得本地副本,而不是仅在原型中的副本。

    var _arrays = [];
    // Copy the properties over onto the new prototype
    for (var name in prop) {
      // ... Existing code ...
    
      if (prototype[name] instanceof Array) {
        _arrays.push(name);
      }
    }
    
    // The dummy class constructor
    function Class() {
      // All construction is actually done in the init method
      if ( !initializing ) {
        for (var i = 0; i < _arrays.length; i++) {
          this[_arrays[i]] = this[_arrays[i]].slice(0);
        }
        if ( this.init ) {
          this.init.apply(this, arguments);
        }
      }
    }
    

    【讨论】:

    • 子对象到底是什么意思?继承该类的类的任何对象?
    • @Py:例如:Class.extend({a: [], b: {c: []}}):它会找到数组a,但不会找到b.c。我找不到更好的描述。
    • 我明白了。据我所知,您的解决方案效果很好:)
    • 作为一个附带问题,您知道对对象执行相同操作的方法吗?这对我来说似乎有点困难(主要是因为使用 [] instanceof Object 也是如此)。
    • @Py:确实,对象很棘手(函数也是对象等等),所以我也没有尝试转换它们。
    【解决方案2】:

    结合 x4u 和 Crescent Fresh 所说的,它看起来像你想要的:

    var Person = Class.extend({ 
    
       init: function(){ 
          this.arrayTest = [];
       },
       arrayModif: function(){
          this.arrayTest.push(4);
          this.arrayTest.push(2);
      }
    });
    

    【讨论】:

    • 是的,这就是我真正的意思。 ;)
    • 是的,但我写道:没有在 init() 中添加任何内容。我知道将 this.arrayTest=[] 放在初始化中是可行的,我只是想知道是否可以在不向 init() 添加任何内容的情况下实现它,而只需更改 John Resig 代码中的某些内容。
    【解决方案3】:

    我还没有使用 John Resig 的代码,但我会尝试在构造函数中设置变量的初始值:

    var Person = Class.extend({ 
      arrayTest:[], 
    
      init: function(){ 
          arrayTest = [];
      }, 
    

    【讨论】:

    • this.arrayTest = []。原型上根本不需要它。
    【解决方案4】:

    同样的问题。我做了这个测试:

    MyClass = Class.extend({
        obj:[],
        addObj: function(obj)
        {
            this.obj[ this.obj.length ] = obj;
        }
    });
    
    instance = new MyClass();
    alert(instance.obj);    // ok: empty
    instance.addObj(123);
    alert(instance.obj);    // ok: alerts 123
    
    instance2 = new MyClass();  // instance 2, empty array is expected
    alert(instance2.obj);   // error: alerts 123, must be empty
    
    instance.addObj(456);
    alert(instance2.obj);   // error: alerts 123,456, must be empty
    

    可能的解决方案(在 Resig 的代码中添加修复,这是一个想法):如果“类”中有数组,您可以将用户的 init() 函数替换为另一个将自动初始化数组的函数,而不是调用用户的 init( )。

    或者您可以在 init() 函数中手动初始化数组,这种解决方案更快(但不安全)。

    MyClass = Class.extend({
        obj:[],
        addObj: function(obj)
        {
            this.obj[ this.obj.length ] = obj;
        }
        init: function()
        {
            this.obj = [];
        }
    });
    

    【讨论】:

      猜你喜欢
      • 2017-10-21
      • 1970-01-01
      • 1970-01-01
      • 2013-11-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-10-03
      • 1970-01-01
      相关资源
      最近更新 更多