Domanda

I am new to web development. Today I learn about classes(function) in javascript. I got an error how to call dynamically added method.

My Code :

<head runat="server">
    <title></title>
    <script type="text/javascript" language="javascript">


    function MyMethod(name, fn) {
        var str = "MyFunction1.prototype." + name + "= fn;";
        eval(str);
    }

    function MyFunction1() {

        MyMethod("start", function () { return "hi"; });

        var abc = this.start(); //gives error 


    }

    </script>
</head>
<body>
    <form id="form1" runat="server" >
    <div>
<input type="button" value="Click" onclick="MyFunction1()"/>

</div>
</form>

Here when I click the input button then not able to call the dynamically added function How can i call the start() function that i added here.

Please Help me. Thanks in Advance.

È stato utile?

Soluzione

this in MyFunction1 referes to the global object in that case(for browsers it is window) , because you call MyFunction1 as function and you don't create an object by using new MyFunction1().

Another thing to be noted. You should not use eval when it is possible to do it without eval.

You can do the same thing using:

function MyMethod(name, fn) {
    MyFunction1.prototype[name] = fn;
}

Using eval prevents you from using optimization tools or tools to validate your code. At least most of these tools don't take eval into account or even give a warning about that you are using it.

Altri suggerimenti

Try adding "new" before your onclick call to MyFunction1, creating an instance of it.

It reseolved I did

Hi , It resolved .Thanks for the gret help i did :

  function fnOnload() {
            MyMethod("start", function () { return "hi"; });
        }

    function MyMethod(name, fn) {
        var str = "MyFunction1.prototype." + name + "= fn;";
        eval(str);
    }

    function MyFunction1() {


    }
    function MyFunction2() 
    {
        var aa = new MyFunction1();
        var answee = aa.start();
    }

and in click of button i callled function MyFunction2()

without changing your code you can do as follow , but I say it would be helpful if you read about invocations types and about this variable.

function MyMethod(name, fn) {
  MyFunction1.prototype[name]= fn;
  return MyFunction1.prototype;
}
function MyFunction1() {
  var myPrototype= MyMethod("start", function () { return "hi"; });
  var returnValue = myPrototype.start();
  console.log(returnValue);
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top