Javascript redefine and override existing function body

后端 未结 8 2069
难免孤独
难免孤独 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 04:04

    When you access a property, system first looks for it in the instance. If it is not found, it looks for it in the prototype. This is why this.hello is being used, rather than O.prototype.hello.

    If you wish to override the implementation of hello, you will need to use JavaScript inheritance. Here is a basic example:

    var A = function(){
        console.log("A is getting constructed");
    };
    
    A.prototype.constructor = A;
    A.prototype.someValue = 1;
    A.prototype.hello = function() {
        console.log("A.hello(): " + this.someValue);
    };
    
    var B = function(){
        //Constructor of A is automatically called before B's
    
        console.log("B is getting constructed");
    };
    B.prototype = new A; //Inherit from A
    B.prototype.constructor = B;
    B.prototype.hello = function() {
        console.log("B.hello() called");
        console.log("Calling base class method");
        A.prototype.hello.call(this);
    };
    
    var a = new A();
    a.hello();
    
    var b = new B();
    b.hello();
    

提交回复
热议问题