简谈 JavaScript、Java 中链式方法调用大致实现原理

         相信,在 JavaScript 、C# 中都见过不少链式方法调用,那么,其中实现该类链式调用原理,大家有没有仔细思考过?其中 JavaScript 类库:jQuery 中就存在大量例子,而在 C# 中,其中 lambda 表达式的大量使用以及扩展方法的新增,使链式调用也见的不少。

         首先,就谈谈 JavaScript 中链式调用,其实,也是就是运用之前提及的 this 。

var Person=function(name,age){
      this.Name=name;
      this.Age=age;
      };

// 为函数 Person 的 prototype 新增 sayName 方法
 Person.prototype.sayName=function(){
    alert(this.Name);

    return this;
 };


// 为函数 Person 的 prototype 新增 sayAge 方法
 Person.prototype.sayAge=function(){
    alert(this.Age);
    return this;
 }

// 在为函数 Person.proetype 新增的方法体,最后,返回的 this 指向以该函数为构造函数所创建的对象
// 从而,形成链式调用


 new Person("jack","20").sayName().sayAge();

 // 注意,Person("jack","20") 如果采用此种调用,此时,this 指向 window ,在浏览器环境中

      另外,再看看 Java、C# 中链式调用的实现原理,大致原理相同,同样是利用 this,不过,在 Java、C# ,this 表示当前对象,而在 JavaScript 中,this 则由运行时确定,并非由定义确定。

      大致即是在每个方法体内,返回 this 、方法返法值类型即为当前类类型,即可实现该功能。

     

public class Person {

    public   String Name;

    public   int Age;


    public  Person(String name,int age){
        this.Name=name;
        this.Age=age;
    }

    public Person sayName(){
        System.out.println (this.Name);
        return this;
    }


    public Person sayAge(){
        System.out.println (this.Age);
        return this;
    }


    public static  void main(String[] args){

        new Person("jack",20).sayAge ().sayName ();
    }


}

      接下来,再看看 C# 中新增扩展方法,通过在静态类中,同时,规定方法第一个参数前含有 this +类型+参数名,从而为该类型对象扩展该方法,从而产生了大量链式调用。

    所以,大家可留意一下,在C#、Java 中,this、base( java 中为 super) 中的使用,同时,也要巧妙运用 JavaScript 中的 this 。

原文地址:https://www.cnblogs.com/Lumia1020/p/5327238.html