Defining new methods to a const object in JS [duplicate] - javascript

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
Is there any way we can add new methods during run-time.
In Java we can do this stack overflow
I just want to know it's possible by just doing using JavaScript?

Javascript is dynamic and there is no compilation involved (other than JIT compiling in the browser, maybe), so things like these are actually trivial and need to happen at runtime:
someObject.newMethod = function(s) { console.log("haha") }
This adds a new method newMethod to an object someObject.
Using the prototype you can add methods to more than just one instance in one step - they will be immediately available to all instances of that prototype.

function are first class citizens in JavaScript.
Execute the following code from Chrome and see the console output;
In the first time the will see the error "TypeError: undefined id not a function" because hello function does not exist.
In the second time no error and we will get "Hello Exits "
var object = {};
try {
object.hello("Does not exit");
}
catch(err) {
console.log(err);
}
object.hello = function(name){
console.log("Hello " + name);
}
try {
object.hello("Exits");
console.log("No error");
}
catch(err) {
console.log(err);
}

I assume you mean adding code dynamically?
It's actually easier to do this in javascript.
It can be done using the eval function.
usage:
eval('code to be run');
example:
HTML
<p id="para">this is a paragraph</p>
javascript
eval('document.getElementById("para").innerHTML = "this is a changed paragraph"');
notice how the javascript inside the eval function is a string.
eval takes a string and evaluates it as javascript.
Warning, assuming you are using javascript on the client-side this is extremely discouraged.
eval will take and run code from anywhere and it is considered a security risk.
If you are using use strict then eval is not allowed.

Yes.
In JavaScript, we have functions are first-class objects and you can manipulate them easily. Combined with the fact that objects are prototype based and not class-based, you can easily add a method to an object. Or to an object's prototype :
//add function to one object :
var object = {};
object.sayHello = function(){
alert("hello");
};
object.sayHello();
//add function to a prototype
//our constructor
function Person(firstName, lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
var p = new Person("John", "Doe");
Person.prototype.sayMyName=function(){
alert("My name is "+this.firstName+ " " + this.lastName);
};
//now all persons can say their name
p.sayMyName();
p2 = new Person("Isaac", "Newton");
p2.sayMyName();
Play with is on jsbin

JavaScript doesn't have compile stage that produces a .class file. The JS code is interpreted by the browser at runtime. Adding a dynamic function is so easy that it's very hard to remember/find how many functions are available on an object.
For example, there is an object globalObj in the globe scope. In file a.js:
globalObj.a = function () { console.log('from a.js'.); }
In file b.js:
globalObj.b = function () { console.log('from b.js'.); }
In a project with hundreds of JS files, you may easily get lost. IDEs are also facing the same problem.

Related

how to make javascript string a function call [duplicate]

This question already has answers here:
How to execute a JavaScript function when I have its name as a string
(36 answers)
Closed 6 years ago.
I have string logo.cr.Button and function
logo.cr.Button = function(){
//something
}
var strg = 'logo.cr.Button';
strg();
now somehow i have to make that string a function call
like strg(); but it is saying
strg is not a constructor
here
Generally when we write JavaScript functions the resulting function declaration looks like this:
function demo() {
// function stuff here
}
You’re probably more than aware that “In JavaScript Functions are first-class Objects”. It’s a phrase that is spouted everywhere, and for good reason. It’s a very powerful idea that has worked to elevate JavaScript to where it is. We’re not going into the details of first-class objects here. All we care about is the fact that, in JavaScript, functions are objects.
This means that the above function can also be declared by calling its Constructor:
var demo = new Function();
Now lets imagine we have a function with parameters and instructions:
function demo(name, age) {
console.log('my name is ' + name);
console.log('my age is ' + age);
}
and now to convert it to Constructor syntax:
var demo = new Function(
"name,age",
"console.log('my name is ' + name);" +
"console.log('my age is ' + age);"
);
This makes it pretty easy to see that these two functions are the same, they are just declared differently. The important difference is that one has easily accessible strings that we should be able to manipulate.
This applies to your function in a very similar way.
var strfunc = new Function ("", "logo.cr.Button()");
I can't seem to format this because I'm on mobile. But i will asap.
Use eval("logo.cr.Button")();
This will execute the function, of course if you have an object like:
var logo = {
cr: {
}
};
This won't work because JavaScript thinks you are using dot notation. When you write logo.cr.Button() JavaScript is looking for a function Button() within the object cr which is in the object logo.
I recommend changing the name to logoCrButton = function()...
You could use eval, but its not recommended.
Secury issues are just one reason, because an user might exploit eval to execute different code that is not supposed to be executed. Within this question it is explained fully.
var logo={cr:{}};
logo.cr.Button = function(){
console.log("something");
}
var string = "logo.cr.Button()";
eval(string);
If you can avoid eval then use a normal function call, an object or an array instead. For insteads Iterating through an array is much better and more stable compared to evaluating some parameters dynamically, as you can see here.
This second example does not use eval, but nevertheless you can call a certain function by using a string:
var obj={logo:{cr:{Button:function(){console.log("something");}}}};
var string = "logo.cr.Button";
function callFunctionByString(string,obj){
var parts = string.split('.');
parts.forEach(function(part){
obj = obj[part];
});
obj();
}
callFunctionByString(string,obj);
Hope this helps.

Add new methods during runtime [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
Is there any way we can add new methods during run-time.
In Java we can do this stack overflow
I just want to know it's possible by just doing using JavaScript?
Javascript is dynamic and there is no compilation involved (other than JIT compiling in the browser, maybe), so things like these are actually trivial and need to happen at runtime:
someObject.newMethod = function(s) { console.log("haha") }
This adds a new method newMethod to an object someObject.
Using the prototype you can add methods to more than just one instance in one step - they will be immediately available to all instances of that prototype.
function are first class citizens in JavaScript.
Execute the following code from Chrome and see the console output;
In the first time the will see the error "TypeError: undefined id not a function" because hello function does not exist.
In the second time no error and we will get "Hello Exits "
var object = {};
try {
object.hello("Does not exit");
}
catch(err) {
console.log(err);
}
object.hello = function(name){
console.log("Hello " + name);
}
try {
object.hello("Exits");
console.log("No error");
}
catch(err) {
console.log(err);
}
I assume you mean adding code dynamically?
It's actually easier to do this in javascript.
It can be done using the eval function.
usage:
eval('code to be run');
example:
HTML
<p id="para">this is a paragraph</p>
javascript
eval('document.getElementById("para").innerHTML = "this is a changed paragraph"');
notice how the javascript inside the eval function is a string.
eval takes a string and evaluates it as javascript.
Warning, assuming you are using javascript on the client-side this is extremely discouraged.
eval will take and run code from anywhere and it is considered a security risk.
If you are using use strict then eval is not allowed.
Yes.
In JavaScript, we have functions are first-class objects and you can manipulate them easily. Combined with the fact that objects are prototype based and not class-based, you can easily add a method to an object. Or to an object's prototype :
//add function to one object :
var object = {};
object.sayHello = function(){
alert("hello");
};
object.sayHello();
//add function to a prototype
//our constructor
function Person(firstName, lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
var p = new Person("John", "Doe");
Person.prototype.sayMyName=function(){
alert("My name is "+this.firstName+ " " + this.lastName);
};
//now all persons can say their name
p.sayMyName();
p2 = new Person("Isaac", "Newton");
p2.sayMyName();
Play with is on jsbin
JavaScript doesn't have compile stage that produces a .class file. The JS code is interpreted by the browser at runtime. Adding a dynamic function is so easy that it's very hard to remember/find how many functions are available on an object.
For example, there is an object globalObj in the globe scope. In file a.js:
globalObj.a = function () { console.log('from a.js'.); }
In file b.js:
globalObj.b = function () { console.log('from b.js'.); }
In a project with hundreds of JS files, you may easily get lost. IDEs are also facing the same problem.

How to use public or internal class in JavaScript in Asp.Net? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I'm working on asp.net web application. I want to use a class in javascript.
in asps.cs file we can easily use this like
ABC obj = new ABC();
obj.name = "John";
Can I use class in same manner in javascript?
If Yes then please tell me How to use public or internal class of same solution in JavaScript Code?
JavaScript doesn't really have classes in the classic sense. There are several workarounds available. A short overview:
Using a function
Using object literals
Singleton using a function
Note there won't really be a way of doing scope modifiers (public/internal/private etc).
You might look into TypeScript and CoffeeScript both compile down to JavaScript, and supports classes. #asawyer pointed out the CoffeeScript idea.
It's worth noting that ECMAScript 6 standard will include support for classes, however the specifications are still a work in progress.
Javascript does have prototype support that can be used as classes as you know from the C# world.
// define a constructor of a class called "ABC"
function ABC() {
this.name = null;
}
// create an instance of a class
var obj = new ABC();
// check instance property value
console.log(obj.name); // outputs "null"
// set instance property value
obj.name = "something";
// some more checks
console.log(obj.name); // outputs "something"
console.log(obj); // outputs whole object
And about public and internal/private classes they may be simulated within function scope (as Javascript only has function scope where C# has block scope as well).
Developers usually put their client logic inside a function, so they create a private scope and avoid any public name clashing or visibility of internal functionality. These scopes can then publicise whathever is required for the general public scope.
Any widely used client library is a great example of such pattern. jQuery or maybe even better AngularJS. It has a lot of internal business logic but just a handful of publically accessible functionality (variable angular being the main one).

Javascript Prototypes (the one like Closures not JQuery)

I just picked up a new book on ASP.NET and AJAX and in it there is a sample like this:
Person = function(firstName) {
this._firstName = firstName;
}
Person.prototype = {
get_FirstName = function() {return this._firstName;}
}
I noticed immediately this is not what I am used to, and FireBug apparently agrees with me that its wonky. I am used to something like:
Person.protoype = {
get_FirstName: function() {return this._firstName;}
}
Is this just a typo on the author's part or is he maybe using a feature from the ASP.NET AJAX library?
Also, is there a difference between the preceding function and this:
Person.protoype.get_FirstName = function() {
return this._firstName;
}
Did the author just smush together two acceptable declarations of the same function?
First question, yes I believe that was a typo.
Second question, yes there is a difference. The ill advised:
Constructor.prototype = { method : function(){} }
inherits from an anonymous object (the {}) in which the method was defined.
If this is done a second time then the previous method would disappear because the inheritance chain would now point to a new anonymous object.
The more usual:
Constructor.prototype.method = function(){}
simply defines a new method.
for your first question yes that is a typo or mistake - it's not valid javascript.
about your last question actually there is a difference between the two examples if there was already something attached to the prototype. The first one, which sets the prototype attribute, will remove anything else that had previously been done to the prototype, while the second merely adds to what's already there. I would (and do) use the second way, adding a new attribute to the prototype.
For the second part of your question, if you use don't assign a new object to the prototype property you can use inheritance:
Person = function( ) {
};
Person.prototype = new Individual( );
Person.protoype.set_LastName = function( lastname) {
this.lastName = lastname
};
//inherited from Individual:
Person.get_FirstName( );
There's a few issues with the example:
Person should be declared with var. It's advisable to always do this with variables.
The typo, noted in other answers.
The getter/setter pattern, likely influenced by C#'s properties. Unless you're doing something complicated, this is probably overkill in JavaScript and your code would be clearer simply using a property. As an aside, the new ECMAScript 5 spec introduced getter and setter methods for properties to the language, and some browsers have implemented them, but they're not yet widespread enough to use on the web.

Declaring functions in JavaScript [duplicate]

This question already has answers here:
var functionName = function() {} vs function functionName() {}
(41 answers)
Closed last year.
What's the difference between these two ways of declaring a function?
function someFunc() { ... }
var someFunc = function() { ... }
I'm not asking in the technical sense. I'm not asking which is better for readability, or which style is preferred.
I am on different opinion with most of the people here. Technically this syntax may mean the same for declaring functions both ways
(I stand incorrect on my last statement. I read up on a diff post why they are technically diff and I'll add in the end, why)
; but the way they play a role in evolving patterns is massive. I would highly recommend "Javascript: The Good Parts" by Doughlas Crockford.
But to prove my point in a subtle and a simple manner; here is a small example.
//Global function existing to serve everyone
function swearOutLoud(swearWord) {
alert("You "+ swearWord);
}
//global functions' territory ends here
//here is mr. spongebob. He is very passionate about his objects; but he's a bit rude.
var spongeBob = {
name : "squarePants",
swear : function(swearWord) {
name = "spongy";
alert("You "+ swearWord);
return this;
}
}
//finally spongebob learns good manners too. EVOLUTION!
spongeBob.apologize = function() {
alert("Hey " + this.name + ", I'm sorry man!");
return this;
}
//Ask spongebob to swear and then apologize in one go (CASCADING EFFECT!!)
alert(spongeBob.swear("twit").apologize());
if you look at the code above I declared a function with a name swearOutLoud. Which would take a swear word from any object or a call and will give you the output. It can do operations on any object using the "this" parameter that is passed to it and the arguments.
However second declaration is declared as an attribute of object called "spongeBob". This is important to note; as here I am moving towards an object driven behavior. While I am also maintaining "cascading effect" as I return "this" if i have nothing else to return.
Somthing similar is done in jquery; and this cascading pattern is important if you are trying to write a framework or something. You'll link it to Builder design pattern also.
But with functions declared as an attributes of an object I am able to achieve an object centric behavior which leads to a better programming paradigm. Unless designed well; individual functions declared outside with global access lead to a non-object oriented way of coding. I somehow prefer the latter.
To see cascading in effect, look at the last statement where you can ask spongebob to swear and apologize at once; even though apologize was added as an attribute later on.
I hope I make my point clear. The difference from a technical perspective may be small; but from design and code evolution perspective it's huge and makes a world of a difference.
But thats just me! Take it or leave it. :)
EDIT:
So both the calls are technically different; because a named declaration is tied to global namespace and is defined at parse time. So can be called even before the function is declared.
//success
swearOutLoud("Damn");
function swearOutLoud(swearWord) {
alert("You " + swearWord)
}
Above code will work properly. But code below will not.
swear("Damn!");
var swear = function(swearWord) {
console.log(swearWord);
}
One advantage of using function someFunc() { ... } is that the function name appears in Firebug debugger. Functions that are declared the other way (var someFunc = function() { ... }) come up as anonymous.
Actually, the difference is that the second declaration gives us the ability to declare functions like this making it possible to have a function as a property for an object :
var myObject=new Object();
myObject.someFunc=function() { ... };
Style wise the second example is more consistent with other common ways to declare functions and therefore it could be argued that it is more readable
this.someFunc = function() { ... }
...
someFunc: function() { ... },
However, as also mentioned it's anonymous and therefore the name does not appear when profiling.
Another way to declare the function is as follows which gets you the best of both worlds
var someFunc = function someFunc() { ... }
Another difference is that, on most browsers, the latter allows you to define different implementations depending on circumstances, while the former won't. Say you wanted cross-browser event subscription. If you tried to define a addEventListenerTo function thusly:
if (document.addEventListener) {
function addEventListenerTo(target, event, listener) {
....
}
} else if (document.attachEvent) {
function addEventListenerTo(target, event, listener) {
....
}
} else {
function addEventListenerTo(target, event, listener) {
....
}
}
on some browsers, all the functions end up being parsed, with the last one taking precedence. Result: the above just doesn't work. Assigning anonymous functions to variables, however, will work. You can also apply functional and basic aspect oriented programming techniques using anonymous functions assigned to variables.
var fib = memoize(function (n) {
if (n < 0) return 0;
if (n < 2) return 1;
return fib(n-1) + fib(n-2);
});
...
// patch the $ library function
if (...) {
$ = around($, fixArg, fixResult);
}
It is both true that the first form:
function test() { }
is a more recognized syntax and that the second form:
var test = function() { ... }
allows you to control the scope of the function (through the use of var; without it, it would be global anyway).
And you can even do both:
var test = function test() { ... test(); ... }
This allows you to define a recursive function in the second form.
For readability, I'd say the first is clearly better. A future maintenance programmer, even assuming they're familiar enough with javascript to know many of the finer points coming up in this thread, are going to assume the first format.
For example, if they should some day want to ctrl-f to search for the definition of your function to see what's happening in there, are they going to first search for someFunc = function() or function someFunc()?
Also, to get downright typographical about it (since we're talking readablity) readers are often scanning the text quickly, and would be more inclined to skip over a line that starts with "var" if they're looking for a function definition.
I know this is a non-technical answer, but it's harder for humans to read code than computers.
When you write
function Test() {
}
JavaScript is really creating a property to which it assigns the function object that once called will execute the code reported in the function definition. The property is attached to the object window, or to the object that contains the function definition.

Categories

Resources