Javascript魔术方法

时间:2013-09-07 17:04:19

标签: php javascript

在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');

通常,您不会将某些内容传递给构造。

我经常遇到的其他一些包括:

__ call()允许您更改调用方法的默认方式。一个很好的例子是覆盖,它允许您在使用任何以单词get开头的方法时获取属性值,或者在方法调用以单词set开始时设置属性值。

__ get()用作类属性的过载器,我不会使用,但有人可能会感兴趣。

__ set()用作类属性的重载,我不会使用,但有人可能感兴趣。

__ destruct()我也不使用,只要没有对特定对象的其他引用,或在关闭序列期间以任何顺序调用。

问题

javascript中有这样的神奇方法吗?

新的javascript程序员应该注意哪些隐藏的宝石,就像我上面描述的php那样?

2 个答案:

答案 0 :(得分:8)

如果“魔术”是指隐式调用的方法,则Javascript包含toStringvalueOf

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

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

然而,在当前的javascript版本中,没有标准的方法来重新定义运算符(php / python魔术方法实际上做了什么)。 Harmony(Javascript 6)将包括proxies API这类工作。 This blog entry提供了关于代理的示例和解释,这里的代码段与php的__get类似:

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

这已在Firefox中使用,如果您转到about:flags并打开实验性JavaScript,则可以使用Chrome支持。

答案 1 :(得分:2)

JavaScript是少数prototypal languages中的一个,Lua也是如此。如果您正在寻找constructor,则会将其命名为(见下文)。 JavaScript中的所有对象都源自base-Object

几乎所有关于JavaScripts魔术 - “方法”的答案都已包含在Hidden features of JavaScript中。访问此StackOverflow站点,了解有关JavaScript的语法和行为以及特性的更多信息,例如comparison operations

以下是一些实用的示例,可帮助您了解行为,(以及在JavaScript对象序列化和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

我写了outline of newer language个功能,但还有许多其他很棒的资源,包括SO,以及我的同行已在此处提供的链接。