Javascript和原型继承问题

时间:2013-11-03 00:33:39

标签: javascript inheritance

有没有办法阻止函数的实例继承属性?我正在阅读有关Javascripts原型对象的文章并阅读以下内容。

“重要的是要注意原型是”实时的“。对象在JavaScript中通过引用传递,因此原型不会与每个新对象实例一起复制。这在实践中意味着什么?这意味着您可以修改任何时候的原型和所有对象(甚至是修改前创建的对象)都将继承这些变化。“

有没有办法阻止所有对象更新。我想保持每个实例的属性都是唯一的。如果没有,还有其他方法可以将属性分配给函数吗?这是我正在使用的一些代码。它允许我在three.js中显示动画精灵,但是当我创建函数的新实例时,实例会跳转到新实例调用的帧。所以都显示相同的帧。我想我是否可以转为继承它应该没问题。对不起,如果它很草率我删除了一堆这个问题不需要的东西。

   function slowToStopFunc(texture, tilesHoriz, tilesVert, numTiles, tileDispDuration) {
       this.tilesHorizontal = tilesHoriz;
       this.tilesVertical = tilesVert;
       this.numberOfTiles = numTiles;
       texture.wrapS = texture.wrapT = THREE.RepeatWrapping; 
       texture.repeat.set( 1 / this.tilesHorizontal, 1 / this.tilesVertical );
       this.tileDisplayDuration = tileDispDuration;
       this.currentDisplayTime = 0;
       this.currentTile = 3;            
           this.update3 = function( milliSec3 ) {
            this.currentDisplayTime += milliSec3;
            while (this.currentDisplayTime > this.tileDisplayDuration && adjustSpeed <= 2)
            {
        if (this.currentTile >= -1 && this.currentTile <= 14) { 
           this.currentTile++;
           }
        }   
        var currentColumn = this.currentTile % this.tilesHorizontal;
        texture.offset.x = currentColumn / this.tilesHorizontal;
        var currentRow = Math.floor( this.currentTile /      this.tilesHorizontal );  
        texture.offset.y = currentRow / this.tilesVertical;
        }    
        }

2 个答案:

答案 0 :(得分:0)

您是否尝试重写继承的属性?不确定您熟悉对象继承的程度,但通常可以通过匹配属性的名称来编写继承的属性。

答案 1 :(得分:0)

原型继承的本质允许您执行此操作,因为属性查找的工作方式。

发生属性查找时:

  1. 对象是否有 someProperty ?如果是,则返回 someProperty
  2. 如果对象没有 someProperty ,请检查它的原型链并执行相同的逻辑,直到它的原型链接为null
  3. 基本上这意味着在对象上设置属性会自然地影响它的继承值。

    function A() {
    }
    
    A.prototype.test = 'test';
    
    var a = new A();
    
    a.test = 'test 2';
    
    console.log(a.test); //not test anymore
    

    但是,如果您询问是否可以在不影响现有实例的情况下修改构造函数的原型,则可能但我不知道您为什么要这样做。

    基本上你只需要替换整个原型实例,这样新创建的实例就有了一个全新的原型对象。

    function A() {}
    
    A.prototype.test = 'test';
    
    var a = new A();
    
    A.prototype = {
        constructor: A,
        test: 'new value'
    };
    
    console.log(a.test); //test
    
    console.log(new A().test); //new value
    
相关问题