神刀安全网

Clojurescript: abstraction and data structure clarification – Part 1

1- Protocols

As define in the documentation ,

A protocol is a named set of named methods and their signatures, defined using defprotocol.

(defprotocol IFoo   "IFoo doc"   (fooA [this] "fooA doc")   (fooB [this] [this a] "fooB doc")) 

You can add documentation for the protocol and for each methods of it. You don’t need to provide methods’ implemantation. After created your protocol, you can implement it in some data using deftype , defrecord or reify .

In our case, we will use deftype because the major difference between deftype and defrecord is that deftype provides just the functionalities implemented by the user, contrary to defmethod that implement a lot of things that won’t help us to understand the javascript generated code.

Let’s see the below example:

Now try to understand how the clojurescript compiler compiles a basic protocol in javascript. UseKLIPSE to see the javascript generated code:

OK! If you are like me, you give me that the generated code is generously hard! So, let’s simplify it:

/**  * Protocol Fly receive a javascript object  * if the object implement fly => call fly  * else throw exception  */ fly = function(this$) {     if(this$._Fly$fly != null) {         return this$._Fly$fly();     } else {         throw "fly not supported!";     } };  /**  * Type Bird that implement fly function  */ Bird = function() {}; Bird.prototype._Fly$fly = function() {     return "Bird uses natural wings."; };  /**  * Type Plane that implement fly function  */ Plane = function() {}; Plane.prototype._Fly$fly = function() {     return "Plane uses metal wings."; };  /**  * Type Empty that not implement fly function  */ Empty = function() {};  /**  * Call Fly.fly for each type you build  */ a380 = new Plane(); eagle = new Bird(); none = new Empty(); console.log(fly.call(null, a380));  console.log(fly.call(null, eagle)); console.log(fly.call(null, none)); 

I hope now it’s more clear, when define a protocol you define a set of functions. Each function receive a javascript object and check if this object implement a specific function. That’s all!

转载本站任何文章请注明:转载至神刀安全网,谢谢神刀安全网 » Clojurescript: abstraction and data structure clarification – Part 1

分享到:更多 ()

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址
分享按钮