繁体   English   中英

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

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

这是创建对象并将函数放置在其中的正确方法吗? 我遇到的每个示例都使用易于理解并在实际情况下有效使用的代码。 所以我正在尝试通过解决这个问题。

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.

您在这里用仅包含myArithmetic的新对象覆盖calc。

您应该正在执行calc.myArithmetic=function(){}; 相反-这会添加一个新属性,将您的函数作为值,这可能就是您想要的。

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

暂无
暂无

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

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