javascript这个对象 [英] javascript this object

查看:82
本文介绍了javascript这个对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

过去4个月我一直在从事网络项目。为了优化代码性能,我们使用了一种模式。我怀疑的是,它是否真的提升了性能?

I have been working on web project for past 4 months. To optimise the code performance we have used a pattern. My doubt is, does it actually boost performance or not?

当我们必须使用这个对象时我们分配它是一个局部变量,并使用它。

when ever we have to use this object we assign it to a local variable, and use that.

function someFunction()
{
  var thisObject = this;
  //use thisObject in all following the code. 
}

这里的假设是,分配这个本地堆栈变量的对象将提升性能。

the assumption here is that, assigning this object to a local stack variable will boost the performance.

我没有在任何地方看到这种类型的编码,所以怀疑它是否没用。

I have not seen this type of coding anywhere so doubt if it is of no use.

编辑:我知道将此对象分配给局部变量是为了保留对象,但这不是我们的情况。

I know that assigning this object to local variable is done for preserving object, but that is not our case.

推荐答案

虽然这是Javascript中的常见做法,但由于性能原因,已完成。在另一个命名本地中保存对象通常是为了在已定义的回调中保留的值在功能内。

While this is a common practice in Javascript it's not done for performance reasons. The saving of the this object in another named local is usually done to preserve the value of this across callbacks which are defined within the function.

function someFunction() {
  var thisObject = this;
  var someCallback = function() {
    console.log(thisObject === this);  // Could print true or false
  };
  return someCallback;
}

是否 thisObject === this 评估为真将取决于它的调用方式

Whether or not thisObject === this evaluates to true will depend on how it's called

var o = {} 
o.someFunction = someFunction();
var callback = o.someFunction();
callback();        // prints false
callback.call(o);  // prints true

这篇关于javascript这个对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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