在对象数据上调用原型函数同时最小化内存使用 [英] Calling a prototype function on an object's data while minimizing memory usage

查看:54
本文介绍了在对象数据上调用原型函数同时最小化内存使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

学习Javascript;我想通过使用原型函数(#2)来减少内存使用量.但是,为了将相关状态/参数从实例传递给原型函数,我需要创建另一个函数(#1).

Learning Javascript; I want to reduce memory usage by using a prototype function (#2). However, in order to pass relevant state/arguments from an instance to the prototype function, I need to create another function (#1).

我知道在 Javascript 中,将为每个 Row 实例创建对象方法 (#1),从而避免重新使用原型函数 (#2) 所节省的内存.如果我用闭包替换函数 #1,也不会节省内存.

I understand that in Javascript, the object method (#1) would be created for each Row instance, negating memory savings from re-using the prototype function (#2). Memory savings would also be negated if I replaced function #1 with a closure.

有没有办法让每个 Row 对象在 Row 自己的唯一状态上调用原型函数,同时仍然最大限度地减少内存使用?

Is there a way for each Row object to call the prototype function on the Row's own unique state while still minimizing memory usage?

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 指向一个新(自动)创建的对象并返回该对象.所以你的函数构造函数应该是这样的:

When using the new keyword, you're basically running your Row() function with this pointing to a newly (and automatically) created object and returning that object. So your function constructor should look like this:

function Row(data) { 
  this.state = data;
}

对象及其原型在使用new时已经被赋值.

The object and its prototype will already be assigned when using new.

然后你可以添加你的原型方法:

Then you can add your prototype methods:

Row.prototype.showInstanceState = function() {
  console.log(this.state);
};

当您作为实例的成员调用方法时,this 将始终指向实例对象(除非您使用 callapply>),所以 this.state 将指向实例自己的属性(您在构造函数中创建的).

When you call methods as members of an instance, this will always point to the instance object (unless you're using call or apply), so this.state will point to the instance own property (which you created in the constructor).

let example = new Row(2);
let example2 = new Row(5);

example.showInstanceState(); // 2
example2.showInstanceState(); // 5

这篇关于在对象数据上调用原型函数同时最小化内存使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆