Learning Javascript;我想通过使用原型函数 来减少内存使用量。但是,为了将相关状态/参数从实例传递到原型函数,我需要创建另一个函数 。
我知道在 Javascript 中,将为每个 Row 实例创建对象方法 ,从而抵消了重用原型函数 节省的内存。如果我用闭包替换函数 #1,内存节省也会被抵消。
有没有办法让每个 Row 对象在 Row 自己的唯一状态上调用原型函数,同时仍然最大限度地减少内存使用量?
function Row(data) {
row = Object.create(Row.prototype);
row.state = data;
//#1
row.showInstanceState = function() {
Row.prototype.showState(this.state);
};
return row;
}
//#2
Row.prototype.showState = function(info) {
console.log(info);
}
let example = new Row(2);
/*
If function #1 didn't exist, the call
below saves memory but we have explicitly pass
in an instance's data at the moment of the call.
*/
example.showState(example.state);
//The call style below is desired, but requires function #1, which would not optimize memory usage.
example.showInstanceState();
使用new
关键字时,您基本上是在运行Row()
函数,this
指向新(自动(创建的对象并返回该对象。所以你的函数构造函数应该看起来像这样:
function Row(data) {
this.state = data;
}
使用new
时,对象及其原型已经分配。
然后,您可以添加原型方法:
Row.prototype.showInstanceState = function() {
console.log(this.state);
};
当您将方法作为实例的成员调用时,this
将始终指向实例对象(除非您使用的是call
或apply
(,因此this.state
将指向实例 own 属性(您在构造函数中创建的属性(。
let example = new Row(2);
let example2 = new Row(5);
example.showInstanceState(); // 2
example2.showInstanceState(); // 5