有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

javascript方法链接会在堆栈中创建中间变量吗?

Method Chaining: as the concept stated, Each method returns an object, allowing the calls to be chained together in a single statement. Chaining is syntactic sugar which eliminates the need for intermediate variables,

只是想知道,方法链接(return a reference to a object)是否在stack中创建了(anonymous? )intermediate variables

在Java中

例如a.functionA().functionB().functionC().functionD()

在上述声明中

A.在a调用functionA之后,JVM是否会在stack中分配一个temporary variable(指向对象B),以便调用下一个函数(如function B

或者只是variable a(in stack)调用函数functionA,然后returned value(address)(stored somewhere else)指向object B中的heapstack中没有创建中间变量

JavaScript中的

例如: Person有一个prototype对象,然后您可以使用prototype访问其中的属性,例如sayHi()function。在这种情况下,Person.prototype.sayHi,这会在堆栈中创建一个中间变量吗


共 (1) 个答案

  1. # 1 楼答案

    这取决于实施情况

    但是,在大多数实现中,链接只是更新当前实例并返回其引用,因此不会创建中间变量

    例:

    public class A {
      private int a;
      private int b;
    
      public A(){}
    
      public A functionA() {
         return this; // In most implementations, the `this` is returned for chaining
      }
    
      public A functionB() {
         return this;
      }
    }