Javascript redefine and override existing function body

后端 未结 8 2060
难免孤独
难免孤独 2020-12-24 03:12

I am wondering can we still change the function body once it is constructed ?

     var O = function(someValue){
           this.hello = function(){
                 


        
8条回答
  •  借酒劲吻你
    2020-12-24 03:57

    Firstly, you need to understand prototypal inheritance.

    When you create an object using O as a constructor, this happens:

    • 1st, a new object is created.
    • 2nd, the hello property of that object is set to a function (via the constructor you defined).
    • 3rd, a secret link from the object, pointing to the O.prototype object, is created.

    When referencing properties of O objects, those properties are first looked for in the object itself. Only if the object doesn't have the property itself does it look up to it's prototype.

    Secondly, you need to understand closures.

    someValue is a variable (not a property) defined in the O function. It can only be accessed from other things that are also defined in the same function (or any functions defined inside the O function). So, we say "someValue was closed over". It can't be accessed by a function that you define outside of O.


    To achieve what you want, you either need to set someValue to a property (which makes it less like a private thing and more like a public thing). Or, you need to define all the functions that need access to someValue inside of O's original definition.

    To change what i.hello points to after i has been created, you need set the property of the object directly.

    i.hello = function () { /* stuff */ };
    

提交回复
热议问题