在PHP中至少在我的实例中,使用魔术方法是很常见的 - 至少在定义核心类时,大多数其他内容都将从中扩展.
php中的魔术方法以常规方法的规范以特殊方式运行.例如,我书中最常用的方法之一就是__construct()
每次加载一个类时都会执行该构造.因此,例如,如果您希望您的类自我介绍,您可能会执行以下操作:
<?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');
Run Code Online (Sandbox Code Playgroud)
通常,您不会将某些内容传递给构造.
我经常遇到的其他一些包括:
__call()允许您更改调用方法的默认方式.一个很好的例子是覆盖,它允许您在使用任何以单词get开头的方法时获取属性值,或者在方法调用以单词set开始时设置属性值.
__get()用作类属性的重载,我不使用,但有人可能会感兴趣.
__set()用作类属性的重载,我不使用,但有人可能会感兴趣.
__destruct()我也不使用,只要没有对特定对象的其他引用,或在关闭序列期间以任何顺序调用.
问题
在javascript里面有这样的神奇方法吗?
有新的javascript程序员应该知道的任何隐藏的宝石,就像我上面描述的PHP吗?
如果通过"魔术"你的意思是隐式调用的方法,Javascript有toString和valueOf:
> foo = {toString: function() { return 'hi' }}
> foo + " there"
"hi there"
> foo = {valueOf: function() { return 100 }}
> foo - 5
95
Run Code Online (Sandbox Code Playgroud)
但是,在当前的javascript版本中,没有标准的方法来重新定义运算符(php/python魔法方法实际上做了什么).Harmony(Javascript 6)将包含用于此类工作的代理API.这个博客文章提供了关于代理的示例和解释,这里有一个类似于php的代码片段__get:
var p = Proxy.create({
get: function(proxy, name) {
return 'Hello, '+ name;
}
});
document.write(p.World); // should print 'Hello, World'
Run Code Online (Sandbox Code Playgroud)
这已经适用于Firefox,如果您转到about:flags并启用实验性JavaScript ,则可以使用Chrome支持.