简体   繁体   中英

Call function within prototype

<script type="text/javascript">

function Test()
{
    console.log('constructor');


    this.chaninFunction = function(){
        console.log('chain me up');
    }
}

Test.prototype.callme = function(first_argument) {
    console.log('called him');

    this.callBack = function()
    {
        console.log('call back');
    }
};

Test.prototype.message = function(first_argument) {
    console.log('message him');
};

var test = new Test();
test.chaninFunction();
test.callme();
test.callme().callBack(); //Error undefined
test.message();

</script>

Hi,

I am learning JS at the moment. having experience few situation.

Is there a way i can call the function within the prototype? the above testing i have done result in error. How can i access the function within prototype, or i can't?

It seems that you're saying you want to be able to chain the .callback() after a call to .callme() .

Chaining is very simple. The previous method you called simply needs to return an object that contains the next method you want to call. So in your case, both methods are on the same object, so you just need to do return this; .

Test.prototype.callme = function(first_argument) {
    console.log('called him');

    this.callBack = function()
    {
        console.log('call back');
    }

    return this;
};

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