this.method = function(){} VS obj.prototype.method = function (){}

前端 未结 1 1415
不知归路
不知归路 2020-12-18 12:17

As a c#/.net dev, I love to toy around with JavaScript in my spare time -- creating my own libraries/frameworks and such. Admittedly, they\'re not much (really nothing more

相关标签:
1条回答
  • 2020-12-18 13:00
    this.method = function(){};
    

    Only works for that specific instance.

    Obj.prototype.method = function(){};
    

    Will work for every instance of Obj

    Though in order to take advantage of prototype you should do

    var o = new Obj(); // Note that functions intended to be used with "new" should be capitalized
    
    o.method();
    

    Dice Example

    I'll assume you intended to return this in your dice() function.

    That example is not really common, because calling a function does not create a new object. In your dice case you would be assigning a method to this, which inside the function is window the global object, and then returning it.

    The outcome would be the same object (window) in both d1 and d2, with a method roll which would be reassigned in the 2nd call.

    To achieve what you want you should create the instances with new, like this:

    var d1 = new Dice(6); // remember capitalization is important here
    var d2 = new Dice(20); 
    

    This will however create 2 roll functions, which is correct but wastes memory since the function can be shared by doing:

    Dice.prototype.roll = function() { /* return random awesomeness */ };
    

    Hope that clarifies things

    0 讨论(0)
提交回复
热议问题