How to “properly” create a custom object in JavaScript?

后端 未结 15 1968
被撕碎了的回忆
被撕碎了的回忆 2020-11-21 08:07

I wonder about what the best way is to create an JavaScript object that has properties and methods.

I have seen examples where the person used var self = this<

15条回答
  •  礼貌的吻别
    2020-11-21 08:23

    When one uses the trick of closing on "this" during a constructor invocation, it's in order to write a function that can be used as a callback by some other object that doesn't want to invoke a method on an object. It's not related to "making the scope correct".

    Here's a vanilla JavaScript object:

    function MyThing(aParam) {
        var myPrivateVariable = "squizzitch";
    
        this.someProperty = aParam;
        this.useMeAsACallback = function() {
            console.log("Look, I have access to " + myPrivateVariable + "!");
        }
    }
    
    // Every MyThing will get this method for free:
    MyThing.prototype.someMethod = function() {
        console.log(this.someProperty);
    };
    

    You might get a lot out of reading what Douglas Crockford has to say about JavaScript. John Resig is also brilliant. Good luck!

提交回复
热议问题