简体   繁体   English

JavaScript,'this' 引用,当从锚标记调用对象函数时

[英]JavaScript, 'this' reference, when calling object function from anchor tag

Here is a simplified version of my JS:这是我的 JS 的简化版本:

var myObject = function() {
    return {
        functionOne: function() {
            //some other logic here
        },
        functionTwo: function() {
            var self = this;
            //some logic here
            //then call functionOne
            self.functionOne();
        }
    };
}

Then I have this in the body of my html:然后我在我的 html 正文中有这个:

<a href="#" onclick="myObject.functionTwo()">click me</a>

Why do I get the error Uncaught TypeError: Object [some url] has no method 'functionOne' , when I click the link?当我单击链接时,为什么会收到错误Uncaught TypeError: Object [some url] has no method 'functionOne'

Your myObject is a function that needs to be called in order to get that objectmyObject是一个函数,需要为了得到这个对象调用

<a href="#" onclick="myObject().functionTwo()">click me</a>

Why not just define myObject as an object:为什么不将myObject定义为一个对象:

var myObject = {
    functionOne: function() {
        //some other logic here
    },
    functionTwo: function() {
        var self = this;
        //some logic here
        //then call functionOne
        self.functionOne();
    }
};

The error that you're seeing doesn't reflect the example code you've shown.您看到的错误并未反映您显示的示例代码。

That said, in the way that you're using the code, you should be able to reduce it to simply:也就是说,按照您使用代码的方式,您应该能够将其简化为:

var myObject = {
    functionOne: function() {
    },
    functionTwo: function() {
        this.functionOne();
    }
}

What you need is for your function to be executed immediately.您需要的是立即执行您的功能。 Further to that your declarion of the self variable leads me to think that you are trying to create a closure so that you can access functionOne from functionTwo.此外,您对self变量的声明使我认为​​您正在尝试创建一个闭包,以便您可以从 functionTwo 访问 functionOne。 If that is the case then I think the following is what you were after:如果是这种情况,那么我认为以下是您所追求的:

var myObject = (function() {

    function func1( ) {
    }

    function func2( ) {
        func1();
    }
    return {
        functionOne: func1,
        functionTwo: func2
    };
}());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM