Saturday, 7 September 2013

Javascript Magic Methods

Javascript Magic Methods

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?

No comments:

Post a Comment