Error : javascript Function Add to class dynamically - javascript

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.

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.

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);
}

Related

CefSharp get result from existing Javascript function

I'm trying to get the result from an existing Javascript function on a local html page, by using CefSharp in a Windows Form application.
The html page source is:
<!DOCTYPE html>
<html>
<body>
<p id="demo">A Paragraph.</p>
<script>
function myFunction() {
document.getElementById("demo").innerHTML = true;
return 1 + 1;
}
</script>
</body>
</html>
My C# code is:
private void ChromeBrowser_LoadingStateChanged(object sender, LoadingStateChangedEventArgs args)
{
if (!args.IsLoading)
{
string result = RunScriptParamAsync("myFunction").ToString();
}
}
public string RunScriptParamAsync(string scriptName)
{
string script = "";
script = scriptName;
//script = string.Format("(function myFunction() {{ document.getElementById('demo').innerHTML = \"{0}\"; return 1 + 1; }})();", scriptName);
chromeBrowser.EvaluateScriptAsync(script).ContinueWith(x =>
{
var response = x.Result;
if (response.Success && response.Result != null)
{
dynamic result = response.Result;
return ((int)result).ToString();
}
else
{
return string.Empty;
}
});
return string.Empty;
}
If I use the commented line
//script = string.Format("(function myFunction() {{ document.getElementById('demo').innerHTML = \"{0}\"; return 1 + 1; }})();", scriptName);
then I'm getting the correct result (2), but the idea is to use a Javascript function already existing on a web page.
A breakpoint inside the function reveals this:
I've also tried
chromeBrowser.GetMainFrame().EvaluateScriptAsync(script)
but with same results.
Any ideas?
You are getting exactly what you are asking for, a reference to the function.You need to append (); to actually execute the function.
//Will return a IJavascriptCallback, which is effectively a function pointer, which is what you have asked for
await browser.EvaluateScriptAsync("myFunction");
//To execute the function you must append ();
await browser.EvaluateScriptAsync("myFunction();")

Access array value from function

I simply want to access the value of array status from another function. However, the alert is giving me value as undefined. Here's my code:
Test.php:
<html>
<body>
<script>
var status=[];
status[0]='1';
calculateInput();
function calculateInput(){
alert(status[0]);
}
</script>
</body>
</html>
You are colliding with window.status:
function calculateInput () {
alert( status === window.status ); // true
}
To avoid this, rename your array or get out of the global scope:
(function IIFE () {
var status = [];
status[0] = "1";
calculateInput();
function calculateInput () {
alert( status[0] );
}
}());
Change your variable name from status to something else
ex.
<html>
<body>
<script>
var mystatus=[];
mystatus[0]='1';
calculateInput();
function calculateInput(){
alert(mystatus[0]);
}
</script>
</body>
</html>

window.onload Javascript, with functions that receives parameter?

I have this function:
<script type="text/javascript">
var car = document.getElementById("Carros").value;
window.onload = ChangeValue(car);
function ChangeValue(str)
{
....
}
See that ChangeValue(str) receives a parameter, how may I make it start in the pageLoad?
using javascript ! The parameter I pass is a <select id="" onChange="ChangeValue(this.value)">
window.onload = function () {
var car = document.getElementById("Carros").value;
ChangeValue(car);
}

Namespace schema for JavaScript

I come from the world of Java. In Java there are packages, for example, "com.mycompany.billing" and classes that are inside the package, for example, "BillProcessor". The company in which I work is starting a new project and I need to decide on a good namespace schema. I'm thinking of projecting how it's done in Java to JavaScript, for example, having a namespace "com.mycompany.billing" and a class that's in a file like "BillProcessor.js". In addition, unit testing is vital so I need such a structure that is easy to unit test.
Can somebody suggest a good approach?
I think that I came up with a good solution, please advise. As an example I'll make a billing page. There are 4 files:
${root}/billing.html - contains an input box for the name on credit card
${root}/js/com/mycompany/common/common.js - initializes logging and error handling
${root}/js/com/mycompany/common/Url.js - class that is used to perform an AJAX call
${root}/js/com/mycompany/aproject/billing.js - initializes things on the billing page
So for example, common.js contains:
var com_mycompany_common_common = function() {
function log(message) {
console.log((new Date()) + ': ' + message);
}
function init() {
window.onerror = function(message) {
log('Unhandled error: ' + message);
}
}
return {
log: log,
init: init
}
} ();
$(document).ready(function() {
try {
com_mycompany_common_common.init();
} catch (e) {
console.log('Error during initialization: ' + e);
}
});
Url.js:
function com_mycompany_common_Url(url) {
this.url = url;
}
com_mycompany_common_Url.prototype.addParameter(name, value) {
this.url += '?' + name + '=' + value;
}
com_mycompany_common_Url.prototype.ajax() {
com_mycompany_common_common.log('Send ajax to: ' + this.url);
}
billing.js
var com_mycompany_aproject_billing = function() {
function init() {
$('#submitButton').click(function() {
Url url = new com_mycompany_common_Url('http://bla.com/process/billing');
var creditCardName = $('#ccName').val();
url.addParameter('name', creditCardName);
url.ajax();
}
}
return {init: init};
} ();
$(document).ready(function() {
try {
com_mycompany_aproject_billing.init();
} catch (e) {
console.log('Error during initialization: ' + e);
}
});
billing.html
<!DOCTYPE html>
<html>
<head>
<title>Billing</title>
</head>
<body>
Enter name on credit card: <input type="text" id="ccName" /><br><br>
<button id="submitButton">Submit Payment</button>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript" src="js/com/mycompany/common/common.js"></script>
<script type="text/javascript" src="js/com/mycompany/common/Url.js"></script>
<script type="text/javascript" src="js/com/mycompany/aproject/billing.js"></script>
</body>
</html>
Most of the time people use the Object Literal pattern to achieve name spacing in JavaScript.
More info: http://msdn.microsoft.com/en-us/scriptjunkie/gg578608
You can "nest" namespaces like so:
var MyCompany = MyCompany || {};
MyCompany.Billing = MyCompany.Billing || {};
// etc...
Another ScriptJunkie article that covers some namespacing stuff: http://msdn.microsoft.com/en-us/scriptjunkie/hh377172.aspx
I'M POSTING THIS QUESTION ON https://codereview.stackexchange.com/questions/8393/approach-to-organizing-javascript-for-an-html-page MAYBE I'LL GET ANSWERS THERE.

Javascript and JQuery "this" scope errors

A sample bit of code:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"></script>
<div id="myinfo">info</div>
<input id="clickme" type="button" value="click here to display info"/>
<script type="text/javascript">
function Fighter() {
this.name = "Kenny"; // fighters name
this.hp = 10; // fighters hp
this.getHP = function() {
return this.hp;
}
this.getName = function() {
return this.name;
}
this.initUpdateButton = function(button_id) {
$(button_id).click(function() {
$("#myinfo").html("Name: "+this.getName()+"<br/>HP:"+this.getHP());
// this.getName is undefined
});
}
};
var me = new Fighter();
alert("Name: "+me.getName()+"<br/>HP:"+me.getHP()); // works properly
me.initUpdateButton("#clickme"); // bind it to some ID
</script>
Simply put, given a JavaScript class with JQuery mixed in, I understand that on the callback for JQuery functions (i.e. $.click()), that this is referring to the object that was clicked and Not the Class or root function(). so this.getName() and this.getHP() don't work.
But what is the best way to get around this problem?
I saw some similar posts but they weren't of use to me so sorry if this is a repost and thanks in advance.
this.initUpdateButton = function(button_id) {
var self = this;
$(button_id).click(function() {
$("#myinfo").html("Name: "+self.getName()+"<br/>HP:"+self.getHP());
});
}

Categories

Resources