在构造函数中使用 'this' 关键字是否会增加整体内存使用量?

Does the use of 'this' keyword within a constructor increase memory usage overall?

例如:

function Constructor() {
  this.peoperty = 1;
  this.myMethod1 = function() {
    //do something
  };
  this.myMethod2 = function() {
    let a = myMethod3();
  }
  
  /*no 'this' keyword for myFunction3,because 
    I am not going to call myFunction3 anywhere else,
    except inside this particular Constructor*/
  myMethod3 = function() {
    let b = 0;
    return b;
  };
}

var hello = new Constructor();

我假设 this 关键字是指创建变量时使用 new 关键字的实例。

问题是,如果myMethod3只会在那个构造函数中调用,我可以使用this 关键字用于 myMethod3,因为我不会在我的代码中的任何地方使用 hello.myMethod3。这是否会在 运行 时节省一些内存,因为我猜只有与 this 关键字绑定的 properties/methods 会占用每个使用 new 关键字创建的实例的内存空间?

在您当前的代码中,您没有声明 myFunction3,因此该函数将在全局范围内,并且 Constructor 的每个新实例都将覆盖之前的 myFunction3:

 const instance = new Constructor();
 myFunction3 = () => alert("whoops");
 instance.myFunction2(); // "whoops"

因此一次只有一个myFunction3,这节省了内存,但是在构造函数中重新声明它没有意义(不声明变量永远没有意义)。


假设您已正确声明它:

 function myFunction3() {
   let b = 0;
   return b;
};

那么你根本不会节省任何内存,因为对 myFunction3 的引用保存在你分配给 this 的其他函数的闭包中,因此 myFunction3 将必须在内存中保留与 this 所指实例一样长的时间。如果你这样做

 this.myFunction3 = function() { /*...*/ };

只要this存在,它也会留在内存中,所以从内存的角度来看它们实际上是相等的。然而 myFunction3 有点 "private" 因为它不能通过 this.

访问

是的,你的猜测是正确的,如果你在构造函数中声明一个方法,每个实例都会有自己的定义:

function Cat() {
  this.meow = function() {
    console.log('meow');
  }
}

const cat1 = new Cat();
const cat2 = new Cat();

cat1.meow();
cat2.meow();

console.log(cat1.meow === cat2.meow);

如果使用原型关键字,则不会发生同样的情况。在这种情况下,两个对象都将有一个指向相同定义的指针:

    function Cat() {
    }
    
    Cat.prototype.meow = function() {
      console.log('meow');
    }

    const cat1 = new Cat();
    const cat2 = new Cat();
    
    cat1.meow();
    cat2.meow();

    console.log(cat1.__proto__.meow === cat2.__proto__.meow);