Gorgo.Live.ToString()

Mariusz, Gorzoch tech Blog

C# extensions method by JavaScript

leave a comment »

Not so many people are aware that extensions method are possible to implemented also on JavaScript code. Here you have quick example how to achieve that:

1. Let’s create class definition

function MyClass(imput){
this.myProperty = input;
}

2. Let’s create object of our class

var myObject = new MyClass('test');

3. Now, we are ready to add first extension method to our MyClass definition

MyClass.prototype.PrintMe = function() { console.log(this.myProperty); }
myObject.PrintMe() //Prints "test"

4. That was easy, but we can go even further and add additional method to all existing objects, by simply extending “Object” class

Object.prototype.PrintMeSuper = function() { console.log("super print!"); }
myObject.PrintMeSuper(); //Print "super print!"

JavaScript can be fun, 😉

Advertisements

Written by Mariusz Gorzoch

23 August 2014 at 15:06

Posted in Bez kategorii

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: