Js prototype , setting name - javascript

I don't mean a name property, e.g
String.prototype.myFunc = function(){}
var myString = new String();
console.log(myString);
When you view the created function in the console, there is a name:''. I was wondering how we set this.

Use a named function:
String.prototype.myFunc = function myFunc(){};

You can construct a function with a function declaration statement and then assign it to the prototype property of your choice:
(function() { // to keep the global scope clean
function myFunc() {
// whatever
}
String.prototype.myFunc = myFunc;
})();
You can in fact give a name to any function in a function instantiation expression, but it's not a super-safe thing to do.

You did you an anonymous function, whose name property is the empty string.
Either use a named function expression:
String.prototype.myFunc = function myNamedFunc(){};
or assign a function which you declared with a name:
function myNamedFunc() {};
String.prototype.myFunc = myNamedFunc;

Related

the name of function return anonymous when I define a function with new Function

I was trying to define a function with constructor Function as below, but why the name of the function return anonymous?
let sayHi = new Function('alert("Hello")');
//this will return anonymous
sayHi.name
This happens because you are creating anonymouse function.
Named functions are initialized with:
function sayHi() {
alert('Hello');
};
sayHi.name // sayHi
...but why the name of the function return anonymous?
Because that's how the Function constructor is defined. This is covered by the spec. The Function constructor calls the abstract operation CreateDynamicFunction, which sets the name to "anonymous" near the end:
Perform SetFunctionName(F, "anonymous").
This is in contrast to a non-dynamic function with no name, which is relatively difficult to create these days because ES2015 defined that names are assigned to functions created with anonymous (!) function expressions in most situations.
The exception is assigning to a property on a pre-existing object:
const o = {};
o.foo = function() { };
console.log(o.foo.name); // ""
Just for completeness, here are some functions that use neither "" nor "anonymous" as their name:
function foo() {
}
console.log(foo.name);
const bar = function() { };
console.log(bar.name);
const baz = () => { };
console.log(baz.name);
(Yes, those second two are assigned a name as specified behavior; see this answer for details.)
Function constructor does not accept a name, therefore it is always anonymous as specified in the docs:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name
Functions created with the syntax new Function(...) or just Function(...) create Function objects and their name is "anonymous".
(new Function).name; // "anonymous"
Hope this helps you!

Why is the value of this variable undefined

I am currently learning javascript and came across this example
var t = function()
{
this.name = "Jam";
no = "123";
}
console.log(t.no); //Undefined
var m = new t();
console.log(m.name);
Why is the first statement undefined ?
t is a function object. As any other object, the function may have properties assigned. So in order your code to work you shall assign "123" to no property of your function (line A):
var t = function()
{
this.name = "Jam";
}
t.no = "123"; // line A
console.log(t.no); // "123"
var m = new t();
console.log(m.name);
Why is the first statement undefined ?
Because t doesn't have a property no.
First of all, the code inside the function, namely
this.name = "Jam";
no = "123";
is only executed when the function is called. You are doing this with var m = new t();, which comes after console.log(t.no);.
Secondly, no = "123"; does not create a property on the function object. It will attempt to set the value of variable no. Since the variable doesn't exist in your example, that line will either create a global variable no, or throw in error if your code is in strict mode.
Consider the following example:
var no = 21;
function foo() {
no = 42;
}
console.log(no); // 21
foo();
console.log(no); // 42
Because t is a function, that would be executed by t();. no on the other hand is a global scooed variable that is reached without prefix from everywhere.
t is a function expression. You you can access a returned object of a function like t().no or you can create a new object by using the function as a constructor like this
myT = new t()
console.log(t.no);
But your no variable is just a global variable inside the function and it is not a part of what it returns nor it is not attached to the returning object of the constructor function.
Here is a very good tutorial which covers all these topics at depths.

Use variable in another function then call the new function

Here I'm trying to use a variable in function New(), the variable was created in the function Test().
I'm still a bit confuse about how to use global variable.
function New(){
Test();
//this show nothing
alert(myName);
}
function Test() {
myName = "John";
}
New();
Even when I do "var myName;" outsise of these functions, it doesn't work.
Still searching
Check this fiddle
things to change :
1) use function New(){} instead of function New{}
2) return myName from test function and store it in new variable in New function
function New(){
var myName= Test();
//this show nothing
alert(myName);
}
function Test() {
var myName = "John";
return myName
}
New();
update : yeah u can also define myName as global variable and use it
When you want to declare a variable for use, use the var keyword. When you do this, the location of where you do it determines the "scope" of the variable. If you want to use the variable in two functions, you can simply declare the variable outside of both:
var myVariable = "Something";
function1(){
myVariable = "something else";
}
function2(){
myVariable = "something else again";
}
Another way to share data is to pass that data as arguments into a function:
function1(){
var myVariable = "Something";
function2(myVariable);
}
function2(someName){
alert(someName); // "Something"
}
In your case, you didn't use the "var" keyword to declare your variable, so it became global, but you have a typo in your code, so it didn't run.
Its just a small type error. Just add braces after New
var myName; // have myName global ie, outside all functions
function New(){ // needs the braces() for New to be a function
Test();
alert(myName);
}
function Test() {
myName = "John";
}
New();
Declare myName globally, then define myName in the return of Test() function. When declaring a function, always use keyword "function", "()", and "{}" no matter what.
var myName;
function New() {
alert(Test());
}
function Test() {
myName = "John";
return myName;
}
New(Test);
Global variable is something whose scope is for a particular class and not restricted to a function.
You can create variable myName inside class but outside function and use it anywhere within class.
var myName="";
function New{
Test();
//this show nothing
alert(myName);
}
function Test() {
myName = "John";
}
New();

Storing a Function in an Object's Property

Let's say I have a JavaScript object, foo, that has a property, "bar", whose value is a function.
var foo = {"bar" : someFunction};
I could replace "someFunction" with an anonymous function. However, what if I wanted to define the function separately:
function someFunction() {
...
}
I can't write foo.bar = someFunction() since it will store the result of evaluating the function.
How can I set foo.bar's value to a function? How would I call it once it's set?
How can I set foo.bar's value to a function?
Without the parentheses:
foo.bar = someFunction;
How would I call it once it's set?
Treat the property as you would any function:
foo.bar();
You should simply assign the bar to some someFunction pointer, like this:
var foo = {};
function someFunction() {
};
foo.bar = someFunction;
foo.bar();
Take out the () and you should be able to set it equal to a function
foo.bar = someFunction; //assign
foo.bar(); // call
http://jsfiddle.net/sN9cs/1/
The first example is exactly how you do it. Just don't call the function:
foo.bar = someFunction;

Declaring variables with this or var?

What is the difference between declaring a variable with this or var ?
var foo = 'bar'
or
this.foo = 'bar'
When do you use this and when var?
edit: is there a simple question i can ask my self when deciding if i want to use var or this
If it is global code (the code is not part of any function), then you are creating a property on the global object with the two snippets, since this in global code points to the global object.
The difference in this case is that when the var statement is used, that property cannot be deleted, for example:
var foo = 'bar';
delete foo; // false
typeof foo; // "string"
this.bar = 'baz';
delete bar; // true
typeof bar; "undefined"
(Note: The above snippet will behave differently in the Firebug console, since it runs code with eval, and the code executed in the Eval Code execution context permits the deletion of identifiers created with var, try it here)
If the code is part of a function you should know that the this keyword has nothing to do with the function scope, is a reserved word that is set implicitly, depending how a function is called, for example:
1 - When a function is called as a method (the function is invoked as member of an object):
obj.method(); // 'this' inside method will refer to obj
2 - A normal function call:
myFunction(); // 'this' inside the function will refer to the Global object
// or
(function () {})();
3 - When the new operator is used:
var obj = new Constructor(); // 'this' will refer to a newly created object.
And you can even set the this value explicitly, using the call and apply methods, for example:
function test () {
alert(this);
}
test.call("hello!"); //alerts hello!
You should know also that JavaScript has function scope only, and variables declared with the var statement will be reachable only within the same function or any inner functions defined below.
Edit: Looking the code you posted to the #David's answer, let me comment:
var test1 = 'test'; // two globals, with the difference I talk
this.test2 = 'test'; // about in the beginning of this answer
//...
function test4(){
var test5 = 'test in function with var'; // <-- test5 is locally scoped!!!
this.test6 = 'test in function with this'; // global property, see below
}
test4(); // <--- test4 will be called with `this` pointing to the global object
// see #2 above, a call to an identifier that is not an property of an
// object causes it
alert(typeof test5); // "undefined" since it's a local variable of `test4`
alert(test6); // "test in function with this"
You can't access the test5 variable outside the function because is locally scoped, and it exists only withing the scope of that function.
Edit: In response to your comment
For declaring variables I encourage you to always use var, it's what is made for.
The concept of the this value, will get useful when you start working with constructor functions, objects and methods.
If you use var, the variable is scoped to the current function.
If you use this, then you are assigning a value to a property on whatever this is (which is either the object the method is being called on or (if the new keyword has been used) the object being created.
You use var when you want to define a simple local variable as you would in a typical function:-
function doAdd(a, b)
{
var c = a + b;
return c;
}
var result = doAdd(a, b);
alert(result);
However this has special meaning when call is used on a function.
function doAdd(a, b)
{
this.c = a + b;
}
var o = new Object();
doAdd.call(o, a, b);
alert(o.c);
You note the first parameter when using call on doAdd is the object created before. Inside that execution of doAdd this will refer to that object. Hence it creates a c property on the object.
Typically though a function is assigned to a property of an object like this:-
function doAdd(a, b)
{
this.c = a + b;
}
var o = new Object();
o.doAdd = doAdd;
Now the function can be execute using the . notation:-
o.doAdd(a, b);
alert(o.c);
Effectively o.doAdd(a, b) is o.doAdd.call(o, a, b)
var foo = 'bar'
This will scope the foo variable to the function wrapping it, or the global scope.
this.foo = 'bar'
This will scope the foo variable to the this object, it exactly like doing this:
window.foo = 'bar';
or
someObj.foo = 'bar';
The second part of your question seems to be what is the this object, and that is something that is determined by what context the function is running in. You can change what this is by using the apply method that all functions have. You can also make the default of the this variable an object other than the global object, by:
someObj.foo = function(){
// 'this' is 'someObj'
};
or
function someObj(x){
this.x=x;
}
someObj.prototype.getX = function(){
return this.x;
}
var myX = (new someObj(1)).getX(); // myX == 1
In a constructor, you can use var to simulate private members and this to simulate public members:
function Obj() {
this.pub = 'public';
var priv = 'private';
}
var o = new Obj();
o.pub; // 'public'
o.priv; // error
Example for this and var explained below:
function Car() {
this.speed = 0;
var speedUp = function() {
var speed = 10; // default
this.speed = this.speed + speed; // see how this and var are used
};
speedUp();
}
var foo = 'bar'; // 'var can be only used inside a function
and
this.foo = 'bar' // 'this' can be used globally inside an object

Categories

Resources