简体   繁体   English

如何在JavaScript中为自定义对象创建带有参数的方法?

[英]How do you create a method with parameters for a custom object in JavaScript?

I have a real problem that I can't solve and I'm really good at computers. 我有一个无法解决的实际问题,而且我真的很擅长计算机。 Building an object using javascript has pushed me over the edge. 使用javascript构建对象使我无所适从。 I have three external js files and the HTML file that initiates the call... 我有三个外部js文件和发起呼叫的HTML文件...

SETUP 1 设置1

popup.HTML FILE Code: popup.HTML FILE代码:

... ...

<script type="text/javascript" src="MethodObjects.js"></script>
<script type="text/javascript" src="popup (test Objects).js"></script>

... ...

MethodObject.js FILE Code: MethodObject.js文件代码:

var URLDisectorO={

    function URLDisector(URL){

        //HERE THE COMPILER SAYS: Unexpected identifier Uncaught ReferenceError:

        //I need to pass a URL into this from another function...
        //test if the URL has google search in it

        var myURL = "" + URL;
        var index = mySearch(myURL, "https://www.google.com/search?q=");

        if(index==-1){
            document.getElementById('currentLink').innerHTML = myURL + "<br /><br />This URL <font color='blue'><b><u><i>WON'T</i></u></b></font> be blocked!";
        }
        else{
            if(index==0){
                document.getElementById('currentLink').innerHTML = myURL + "<br /><br />This URL <font color='red'><b><u><i>WILL</i></u></b></font> be blocked!";
            }
            else{
                return "ERROR";
            }
        }
    }

    function mySearch(str, str1){

    //Searches the URL for the two strings passed in...

        var index=-1;
        var strlength=str.length;
        var str1length=str1.length;
        var length=0;

        if(strlength>str1length){
            length=str1length;
        }
        else length=strlength;

        for(var i=0; i<length; i++){

            if(str.charAt(i)==str1.charAt(i)){

                if(i>index && index==-1 && i<1){
                    index=i;
                }

                for(var j=i; j<length-1; j++){
                    if(str.charAt(j+1)==str1.charAt(j+1)){
                        i=j;
                        break;
                    }
                    else{
                        index=-1;
                        break;
                    }
                }//end of inner for loop

                if(index==-1){
                    break;
                }
            }
        }//end of outer for loop

        if(index>0){
            return -1;
        }
        else{
            return index;
        }
    }//end my search method
}

popup (Object Methods test).js FILE Code: 弹出窗口(对象方法测试).js文件代码:

//This is the file doing the calling and passing in stuff to the other file above...

//The HTML file called the JS file and it starts and it works until it gets down to...

var txtU="";

function getURL(){
chrome.tabs.getSelected(null, function(tab) {
    var URL="";
    document.getElementById('currentLink').innerHTML = tab.url;
    URL = "" + document.getElementById('currentLink').innerHTML;
    txtU+=URL;
    alert("The URL is:\n\n" + txtU);
    URLDisectorO.URLDisector(txtU);
    //Object Call Here!
    //HERE THIS DOESN'T WORK!!!
    //The compiler says: Uncaught SyntaxError: URLDisectorO is not defined.

});
}

getURL();//The Call! The main method's call!

The thing that bothers me is: popup.js FILE Code works when it is the only external .js File and this line of code is in the HTML FILE... 让我感到困扰的是:popup.js FILE代码在它是唯一的外部.js文件且此行代码在HTML FILE中时起作用。

SETUP 2 设置2

HTML FILE CODE: HTML文件代码:

... ...

<script type="text/javascript" src="MethodObjects.js"></script>

... ...

popup.js File Code: popup.js文件代码:

var txtU="";

function getURL(){
chrome.tabs.getSelected(null, function(tab) {
    var URL="";
    document.getElementById('currentLink').innerHTML = tab.url;
    URL = "" + document.getElementById('currentLink').innerHTML;
    txtU+=URL;
    alert("The URL is:\n\n" + txtU);
    URLDisector(txtU);
});
}

getURL();//The Call! The main method's call!

function URLDisector(URL){

    var myURL = "" + URL;
    var index = mySearch(myURL, "https://www.google.com/search?q=");

    if(index==-1){
        document.getElementById('currentLink').innerHTML = myURL + "<br /><br />This URL <font color='blue'><b><u><i>WON'T</i></u></b></font> be blocked!";
    }
    else{
        if(index==0){
            document.getElementById('currentLink').innerHTML = myURL + "<br /><br />This URL <font color='red'><b><u><i>WILL</i></u></b></font> be blocked!";
        }
        else{
            return "ERROR";
        }
    }
}

function mySearch(str, str1){

    var index=-1;
    var strlength=str.length;
    var str1length=str1.length;
    var length=0;

    if(strlength>str1length){
        length=str1length;
    }
    else length=strlength;

    for(var i=0; i<length; i++){

        if(str.charAt(i)==str1.charAt(i)){

            if(i>index && index==-1 && i<1){
                index=i;
            }

            for(var j=i; j<length-1; j++){
                if(str.charAt(j+1)==str1.charAt(j+1)){
                    i=j;
                    break;
                }
                else{
                    index=-1;
                    break;
                }
            }//end of inner for loop

            if(index==-1){
                break;
            }
        }
    }//end of outer for loop

    if(index>0){
        return -1;
    }
    else{
        return index;
    }
}//end of method

The thing is: I want to use objects so that I have access to these methods all the time instead of just one specific case... Objects would make this code a little more flexible... calling them where needed (SETUP 1 - popup (Object Methods test).js) though I still want to keep the setup above and not have to revert to the setup below... 问题是:我想使用对象,以便我可以一直访问这些方法,而不仅仅是一种特定的情况...对象会使代码更灵活...在需要的地方调用它们(设置1-弹出窗口(对象方法test).js),尽管我仍然想保留上面的设置,而不必恢复到下面的设置...

Any help and error fix instructions would be greatly appreciated! 任何帮助和错误修复说明将不胜感激!

I can't really understand your problem because as Sam I am said, you have posted way too much information. 我真的无法理解您的问题,因为正如萨姆所说,您发布的信息太多了。 However, I think that you have included the js files in a wrong order inside the html file. 但是,我认为您在html文件中以错误的顺序包含了js文件。 Try writing : 尝试写作:

<script type="text/javascript" src="popup.js"></script>

above all the other. 最重要的是

Also, take some time to edit your question. 另外,请花一些时间来编辑您的问题。 Make it shorter and more clear. 使它更短,更清晰。

You need to use a better design pattern for your JavaScript based web application. 您需要为基于JavaScript的Web应用程序使用更好的设计模式。 I would recommend taking a look at the JavaScript: The Good Parts , by Douglas Crockford. 我建议您看一下Douglas Crockford的JavaScript:The Good Parts

As a hacky approach, you can always have a global object that stores reference to your methods, but I would not recommend taking this approach for the long run. 作为一种骇人听闻的方法,您始终可以拥有一个存储对您的方法的引用的全局对象,但是从长远来看,我不建议您采用这种方法。

var foo = function () {
    alert("hello world");
};

var globalContext = { 
    fooMethod : foo,
};

Now, you can access it as globalContext.fooMethod(); 现在,您可以将其作为globalContext.fooMethod();访问globalContext.fooMethod(); . The {} in JavaScript create objects which store key->value pairs, and values can be methods among other types. JavaScript中的{}创建存储键->值对的对象,值可以是其他类型中的方法。

Hope this helps! 希望这可以帮助!

Thanks to the comment from HUGO on: attach get/set function to objects property in js , I was able to understand what I needed to do. 感谢HUGO的评论: 将get / set函数附加到js中的objects属性 ,我能够理解我需要做的事情。

Here is the solution: 解决方法如下:

I needed to create a variable and store a function in it. 我需要创建一个变量并在其中存储一个函数。 The function, stored inside the variable, serves as the object encapsulation structure (sorry about my vocabulary--I might use words in the wrong context though with good intent). 该函数存储在变量中,用作对象封装结构(对我的词汇感到抱歉-我可能出于错误的意图使用了错误的上下文中的单词)。 Then I needed to create an instance of this object in another class. 然后,我需要在另一个类中创建此对象的实例。 From then on I could have access to the methods and variables provided inside that object. 从那时起,我可以访问该对象内部提供的方法和变量。

Look at the code to see what is different. 查看代码,看看有什么不同。 The comments will guide you and tell you why that had to be instead... 这些评论将指导您,并告诉您为什么必须这样做...

popup.HTML FILE Code: popup.HTML FILE代码:

... ...

<script type="text/javascript" src="MethodObjects.js"></script>
<script type="text/javascript" src="popup (test Objects).js"></script>

... ...

MethodObject.js FILE Code: MethodObject.js文件代码:

var global=function(){ //The declaration of a global variable set to a function object value...
    var URL="";

    this.URLD=function URLDisector(URL){ //This is different.

/*With this in front of the property name... this displays the correct format of how to include a function as a property of the Object...

*The correct way to call a method inside this object is:
*
*this.propertyName(parameter); OR this.propertyName();
*
*Though a correct declaration of this looks like:
*
*this.URLD=function URLDisector(URL){
*...code inside the method...
*};
*/
        var myURL = "" + URL;
        var index = this.search(myURL, "https://www.google.com/search?q="); //This is different.

        if(index==-1){
            document.getElementById('currentLink').innerHTML = myURL + "<br /><br />This URL <font color='blue'><b><u><i>WON'T</i></u></b></font> be blocked!";
        }
        else{
            if(index==0){
                document.getElementById('currentLink').innerHTML = myURL + "<br /><br />This URL <font color='red'><b><u><i>WILL</i></u></b></font> be blocked!";
            }
            else{
                return "ERROR";
            }
        }
    }
    //end first inside Function

    this.search=function mySearch(str, str1){ //This is different.

        var index=-1;
        var strlength=str.length;
        var str1length=str1.length;
        var length=0;

        if(strlength>str1length){
            length=str1length;
        }
        else length=strlength;

        for(var i=0; i<length; i++){

            if(str.charAt(i)==str1.charAt(i)){

                if(i>index && index==-1 && i<1){
                    index=i;
                }

                for(var j=i; j<length-1; j++){
                    if(str.charAt(j+1)==str1.charAt(j+1)){
                        i=j;
                        break;
                    }
                    else{
                        index=-1;
                        break;
                    }
                }//end of inner for loop

                if(index==-1){
                    break;
                }
            }
        }//end of outer for loop

        if(index>0){
            return -1;
        }
        else{
            return index;
        }
    }
    //end my search method
};

popup (Object Methods test).js FILE Code: 弹出窗口(对象方法测试).js文件代码:

var txtU="";

var g = new global(); /*This is different.
This line declares that:
We have an object with the instance name "g"
"g" contains the properties found inside the object or class called "global".*/

function getURL(){
    chrome.tabs.getSelected(null, function(tab) {
        var URL="";
        document.getElementById('currentLink').innerHTML = tab.url;
        URL = "" + document.getElementById('currentLink').innerHTML;
        txtU+=URL;
        alert("The URL is:\n\n" + txtU);

        g.URLD(txtU);

/*This is different.
*This line says that we want to call the object name and, in this case,
*call the method property name "URLD" and pass in "txtU" as the parameter to it.
    });
}

getURL(); //The Call! The main method's call!

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

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