简体   繁体   中英

OOP javascript and Simple Class Instantiation

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

Modified version

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

Why should I use the object's prototype to add a method (after making an instance) instead of writing it inside the constructor ?

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.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM