Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript Magic Methods

Tags:

javascript

php

In php at least in my instance, it is very common to use magic methods -- at least when defining your core classes from which most of everything else will extend from.

Magic methods in php act in a special way from the norm of your regular methods. For example one of the most common methods in my book to play with would be the __construct()

The construct is executed every time a class has been loaded. So for instance if you wanted your class to introduce itself you might do something like this:

<?php
class Person 
{
    function __construct($name)
    {
        $this->name = $name;
        $this->introduceYourself();
    }

    public function introduceYourself()
    {
        //if $this->name then echo $this->name else echo i dont have name
        echo $this->name ? "hi my name is " . $this->name : "error i dont have name";
    }
}

$dave = new Person('dave');

Typically you wouldn't pass something to the construct.

Some other ones that I run across semi-commonly include:

__call() which allows you to change the default way that methods are called. A good example is an override that allows you to get attribute values whenever you use any method that starts with the word get, or setting attribute values whenever a method call starts with the word set.

__get() used as an over loader for class attributes, i don't use but someone may be interested.

__set() used as an overloader for class attributes, i don't use but someone may be interested.

__destruct() i also do not use, called as soon as there are no other references to a particular object, or in any order during the shutdown sequence.

The Question

Are there magic methods like this inside of javascript?

Are there any hidden gems that a new javascript programmer should be aware of like the ones i've described above for php?

like image 672
ajameswolf Avatar asked Sep 07 '13 17:09

ajameswolf


2 Answers

If by "magic" you mean methods that are called implicitly, Javascript has toString and valueOf:

> foo = {toString: function() { return 'hi' }}
> foo + " there"
"hi there"

> foo = {valueOf: function() { return 100 }}
> foo - 5
95

However, there's no standard way to redefine operators (what php/python magic methods actually do) in current javascript versions. Harmony (Javascript 6) will include proxies API for this kind of work. This blog entry provides examples and explanations on Proxies, here's a snippet from there that works similar to php's __get:

var p = Proxy.create({
  get: function(proxy, name) {
    return 'Hello, '+ name;
  }
});
document.write(p.World); // should print 'Hello, World'

This already works in Firefox, Chrome support is available if you go to about:flags and turn on experimental JavaScript.

like image 154
georg Avatar answered Sep 22 '22 06:09

georg


JavaScript is one of few prototypal languages, as is Lua. If you are looking for the constructor, it is named such (see below). All objects in JavaScript are derived from the base-Object.

Virtually all your answers in regard to JavaScripts magic-"methods", have already been included in Hidden features of JavaScript. Visit this StackOverflow site to learn a bit more about JavaScript's syntax and behavior as well as peculiarities, for instance in regard to comparison operations.

Following are some hands-on examples to help you understand the behavior, (and circular references when it comes to serialization of JavaScript objects and importing them in PHP).

0 .constructor
function Number() { [native code] }

0 .constructor(10)
>> 10

var myObj = function(){ console.log("I am a new function"); }
>> undefined
myObj.constructor
>> function Function() { [native code] }
myObj.constructor()
>> function anonymous() {}
myObj.prototype.constructor()
>> I am a new function

myObj === myObj.prototype.constructor
>> true

x = new myObj
>> I am a new function
<< myObj {}

x.constructor()
>> I am a new function
<< undefined

I wrote an outline of newer language features, but there are many other great resources including SO, and the links already provided by my peers in here.

like image 34
Lorenz Lo Sauer Avatar answered Sep 18 '22 06:09

Lorenz Lo Sauer