简体   繁体   English

这是使用带有函数的对象的正确方法吗?

[英]Is this the correct way to use an object with a function inside it?

Is this the correct way to create an Object and place a function inside of it? 这是创建对象并将函数放置在其中的正确方法吗? Every example I come across uses code that is to simple to understand and to use effectively in an actual situation. 我遇到的每个示例都使用易于理解并在实际情况下有效使用的代码。 So I'm trying to figure this out by doing. 所以我正在尝试通过解决这个问题。

function calc() //creating an empty object named calc
{
}

var calc = new calc(); //creating a new instance of the calc object

calc.arithmetic = function maths (input) 
{
    var str = input;
    var a=str.substr(1,1); 
    var b=str.substr(2,1);
    var c=str.substr(3,1);

    if(b == "+")
    {
        answerNumber = a + c;
    }
    else if(b == "-")
    {
        answerNumber = a + c;
    }
    else if(b == "*")
    {
        answerNumber = a * c;
    }
    else if(b == "/")
    {
        answerNumber = a / c;
    }
}
document.getElementById("input").value=answerNumber;




document.write(calc.arithmetic(input))  //calling the method in the context of the object.

You're overwriting calc with a fresh object containing only myArithmetic here. 您在这里用仅包含myArithmetic的新对象覆盖calc。

You should be doing calc.myArithmetic=function(){}; 您应该正在执行calc.myArithmetic=function(){}; instead - this adds a new property with your function as value, which is probably what you want. 相反-这会添加一个新属性,将您的函数作为值,这可能就是您想要的。

我将看看Douglas Crockford网站(http://www.crockford.com/javascript/private.html)。

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

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