OOP javascript和简单类实例化

OOP javascript和简单类实例化

问题描述:

首先,如果这是一个愚蠢的问题,我很抱歉。我已经写了两个代码片段。从 此处 找到的第一个代码段,由 John撰写Resig 并且毫无疑问他是最好的之一,我从原始代码修改了第二个代码片段只是为了理解差异,但我不确定实际上两者之间有什么区别我能做什么并不能与两者相比。请有人帮我理解差异。谢谢。

First of all I'm sorry if this is a stupid question. I've written two code snippets bellow. The first code snippet found from here written by John Resig and undoubtedly he's one of the bests and the second code snippet is modified by me from the original code only to understand the difference but I'm not sure actually what is the difference between both and what I can and can't do with both comparatively. Please someone help me to understand the difference. Thanks.

    function makeClass(){
        return function(args){
            if ( this instanceof arguments.callee ) {
                if ( typeof this.init == "function" )
                    this.init.apply( this, args.callee ? args : arguments );
                }
                else  return new arguments.callee( arguments );
        };
    }
    var User = makeClass();
    User.prototype.init = function(first, last){
      this.name = first + " " + last;
    };
    var user = User("John", "Resig");
    console.log(user);

修改后的版本

    function myClass(args)
    {
        if (this instanceof arguments.callee) 
        {
            this.init = function(first, last){
                this.name = first + " " + last;
            };
            this.init.apply( this, args.callee ? args : arguments );
        }
        else    return new arguments.callee( arguments );
    }
    var obj = new myClass('Sheikh', 'Heera');
            console.log(obj);

我为什么要使用对象的原型来添加方法(在制作实例之后)在构造函数中写入它?

在对象的原型上定义方法而不是在构造函数是原型中定义的方法立即可用于(在内存中)共享对象的所有实例。

A primary reason to define a method on the object's prototype rather than in the constructor is that the method defined in the prototype is immediately available to and shared by (in memory) all instances of the object.

通过在构造函数中定义方法,该方法特定于创建它的对象的实例。如果你实例化10个你的对象,你将在内存中有10个副本,即使它们都是相同的,直到你修改其中一个。

By defining the method in the constructor, that method is specific to the instance of the object creating it. If you insantiate 10 of your object, you'll have 10 copies of the method in memory, even though they are all the same, until you modify one of them.

但是,要清楚,通过对象实例中的 shared ,我并不是说该方法在它访问的任何属性上静态运行。这些属性(如果使用 this。定义)仍然是特定于实例的。只是你不会最终定义同一方法的多个副本。

To be clear though, by shared among object instances, I do not mean to say that the method operates statically on any properties it accesses. Those properties (if defined with this.) are still instance-specific. It's just that you don't end up defining multiple copies of the same method.