在原型中调用函数

时间:2014-03-05 23:57:23

标签: javascript

<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>

您好,

我正在学习JS。经历很少的情况。

有没有办法可以在原型中调用函数?上面的测试我做错了。我如何在原型中访问该功能,或者我不能?

1 个答案:

答案 0 :(得分:0)

您似乎希望能够在致电.callback()后链接.callme()

链接非常简单。您调用的上一个方法只需返回一个包含您要调用的下一个方法的对象。因此,在您的情况下,两个方法都在同一个对象上,因此您只需要return this;

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

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

    return this;
};
相关问题