Related
I was recently introduced into learning JavaScript and I was literally confused when I went through the prototype concepts. Everything I read and understood got confused.
Let be get straight through..
I have two questions related to functions and Objects.
Question 1:
Can functions in JS have (key, value) pair of property in it? If so, what might me the data type of the key? Because In an Object, the key of the property can be only of the types String, Object and in some special cases Symbol.
Question 2:
How are the functions evaluated internally? Are they converted to objects?
function sample () {
// code goes here
}
and
let myFunc = new Function(,,);
Thanks
It seems your overall question is “what are functions”.
Yes, functions are objects*. That’s why they are first-class citizens. They are just like any other value. Just like other objects they can have properties (you might be familiar with f.call, f.bind, etc).
What distinguishes functions from other objects is that they have an internal [[Call]] property (internal properties cannot be accessed from user code, they are used in the specification to define internal state/behavior of objects).
The [[Call]] property contains some representation of the code in the body of the function. It’s this code that is executed when the function is called.
There are other internal properties needed for a function to work, but [[Call]] is the most important one. It is used to determine whether an object is callable or not.
Prototypes are not primarily related to functions. Prototypes are a concept applying to objects in general. They are not very complicated either: a prototype is a just an object. What makes an object a prototype is that another object has a reference to it via its internal [[Prototype]] property. Then we can say “this object is the prototype of the other object”.
Other languages work similarly. Python for example lets you make instances of classes callable by implementing the magic def __call__: method.
*: There are seven data types in JavaScript:
Boolean
Number
String
Null
Undefined
Symbol
Object
The first six are so called “primitive” data types.
You can add properties at will to a function, as in JavaScript functions are objects. In both of the syntaxes you provided for creating a function, you get a (function) object.
Example of adding properties:
function counter() {
console.log(++counter.count);
}
counter.count = 0; // create a property on the function object
// Call the function several times
counter();
counter();
counter();
As functions are objects, the same restrictions apply: property names are strings. Values can be anything. Properties are not ordered.
Answer to Question 1:
Yes, you can have key: value pair inside a function, but that function is called constructor. For example:
function Car(make, model, year) {
this.make = make;
this.model = model;
this.year = year;
}
In ES6: you can store similar key:value pair using constructor() function inside a class. For example:
constructor(make, modal, year) { // constructor syntactic sugar
this.make = make;
this.model = model;
this.year = year;
}
The data-type of key depends on what type of value you're storing in that key. In our example, if I store string value in this.model, data-type of model key would be string and If I store year as a number then data-type of this.year would be number.
Answer to Question 2
To understand how a function works internally, you need to understand execution context. To understand execution context, you must read this article by David. To simply put:
Every time a function is called, a new execution context is created. However, inside the JavaScript interpreter, every call to an execution context has 2 stages:
Creation Stage
[when the function is called, but before it executes
any code inside]: Create the Scope Chain. Create variables, functions
and arguments. Determine the value of "this".
Activation / Code
Execution Stage: Assign values, references to functions and interpret
/ execute code.
My best advice would be to jump into Chrome console and play there. Really good way to fit bricks in their places.
Can functions in JS have (key, value) pair of property in it? If so,
what might me the data type of the key? Because In an Object, the key
of the property can be only of the types String, Object and in some
special cases Symbol.
Sure they can. But you misunderstood something about Object as a key. You can do this:
var obj = {};
var key = {};
obj[key] = "Smthg";
But that would work just because key would be stringified. So obj[key] would be converted into obj["[object Object]"]. Test it out:
var obj = {};
var key = {};
obj[key] = "key1";
obj["[object Object]"] = 'key2';
console.log(obj[key]);
As you see, no matter how many objects you will use as a key - they will override each other.
How are the functions evaluated internally? Are they converted to
objects?
JS is OOP language - everything is an object (except some primitives etc.). So that means there are many different objects. And they inherit something from each other, otherwise there would be a one GIANT object with all those properties bounded and endless waiting time to load your first "Hello World" application.
My probably best tool to learn JS, after taking some readings is console.dir() method (or just dir(someVar) if in console mode).
Create object - var f = new Function() and dir(f) to see what is it and what is its prototype etc.
Now its a good question , which can confuse many. First thing there is the concept of constructor and prototype in javascript
So
function A() {
console.log("A")
}
if you console.log(typeof(A)) // "function"
now A has also a protoype
console.log("Aprototype", A.prototype)
that will be an object
That native object has a property proto
console.log(A.prototype.__proto__)
This will be parent prototype. from which the current prototype is inheriting. This parent prototype will also have a constructor, That is your Function constructor
console.log("parentConstructor", A.prototype.__proto__.constructor)
Now this parent Protype has also one more proto, which is linked to Object function constructor
console.log("parent parent __proto__", A.prototype.__proto__.__proto__)
and its constructor is your Object constructor function.
Thats why you are able to get new object
var t = new Object()
Look how we have called it like constructor.
Thats how prototypical javascript is :)
I've done a lot of searching and some playing around, and I'm pretty sure the answer to this question is no, but I'm hoping a JavaScript expert might have a trick up his sleeve that can do this.
A JavaScript function can be referenced by multiple properties, even on completely different objects, so there's no such thing as the object or property that holds the function. But any time you actually call a function, you must have done so via a single object (at the very least, the window object for global function calls) and property on that object.
(A function can also be called via a function-local variable, but we can consider the function-local variable to be a property of the activation object of the scope, so that case is not an exception to this rule.)
My question is, is there a way to get that property name that was used to call the function, from inside the function body? I don't want to pass in the property name as an argument, or closure around a variable in an enclosing scope, or store the name as a separate property on the object that holds the function reference and have the function access that name property on the this object.
Here's an example of what I want to do:
var callName1 = function() { var callName = /* some magic */; alert(callName); };
var obj1 = {'callName2':callName1, 'callName3':callName1 };
var obj2 = {'callName4':callName1, 'callName5':callName1 };
callName1(); // should alert 'callName1'
obj1.callName2(); // should alert 'callName2'
obj1.callName3(); // should alert 'callName3'
obj2.callName4(); // should alert 'callName4'
obj2.callName5(); // should alert 'callName5'
From my searching, it looks like the closest you can get to the above is arguments.callee.name, but that won't work, because that only returns the name that was fixed to the function object when it was defined, and only if it was defined as a named function (which the function in my example is not).
I also considered that maybe you could iterate over all properties of the this object and test for equality with arguments.callee to find the property whose value is a reference to the function itself, but that won't work either (in the general case), because there could be multiple references to the function in the object's own (or inherited) property set, as in my example. (Also, that seems like it would be kind of an inefficient solution.)
Can this be done?
Short answer:
No, you cannot get "the property name" used to call your function.
There may be no name at all, or multiple names across different scopes, so "the property name" is pretty ill defined.
arguments.callee is deprecated and should not be used.
There exists no solution that does not use arguments or closure.
Long answer:
As thefourtheye commented, you should rethink what you are trying to do and ask that instead in a new question. But there are some common misconceptions, so I will try to explain why you cannot get the "simple property name".
The reason is because it is not simple.
Before we go ahead, let us clarify something. Activation Objects are not objects at all.
The ECMAScript 5.1 specification calls them Environment Records (10.2.1), but a more common term is Scope chain.
In a browser the global scope is (often) the window object, but all other scopes are not objects.
There may be an object that you use to call a function, and when you call a function you must be in some scope.
With few exceptions, scopes are not objects, and objects are not scopes.
Then, there are many names.
When you call a function, you need to reference it, such as through an object property. This reference may have a name.
Scope chain has declarations, which always have a name.
A Function (the real function, not reference) may also have a function name - your arguments.callee.name - which is fixed at declaration.
Not only are they different names, they are not (always) the "the property name" you are seeking.
var obj = { prop : function f(){} }, func = obj.prop;
// "obj" and "func" are declarations.
// Function name is "f" - use this name instead of arguments.callee
// Property name is "prop"
func(); // Reference name is "func"
obj.prop(); // Reference names are "obj" and "prop"
// But they are the same function!
// P.S. "this" in f is undefined (strict mode) or window (non-strict)
So, a function reference may comes from a binding (e.g. function declaration), an Object (arguments.callee), or a variable.
They are all References (8.7). And reference does have a name (so to speak).
The catch is, a function reference does not always come from an object or the scope chain, and its name is not always defined.
For example a common closure technique:
(function(i){ /* what is my name? */ })(i)
Even if the reference does have a name, a function call (11.2.3) does not pass the reference or its name to the function in any way.
Which keeps the JavaScript engine sane. Consider this example:
eval("(new Function('return function a(){}'))()")() // Calls function 'a'.
The final function call refers the eval function, which refers the result of a new global scope (in strict mode, anyway), which refers a function call statement, which refers a group, which refers an anonymous Function object, and which contains code that expresses and returns a function called 'a'.
If you want to get the "property name" from within a, which one should it get? "eval"? "Function"? "anonymous"? "a"? All of them?
Before you answer, consider complications such as function access across iframes, which has different globals as well as cross origin restriction, or interaction with native functions (Function.prototype.bind for example), and you will see how it quickly becomes hell.
This is also why arguments.caller, __caller__, and other similar techniques are now all deprecated.
The "property name" of a function is even more ill defined than the caller, almost unrealistic.
At least caller is always an execution context (not necessary a function).
So, not knowing what your real problem is, the best bet of getting the "property name" is using closure.
there is no reflection, but you can use function behavior to make adding your own fairly painless, and without resorting to try/catch, arguments.callee, Function.caller, or other strongly frowned-upon behavior, just wasteful looping:
// returning a function from inside a function always creates a new, unique function we can self-identify later:
function callName() {
return function callMe(){
for(var it in this) if(this[it]===callMe) return alert(it);
}
};
//the one ugly about this is the extra "()" at the end:
var obj1 = {'callName2':callName(), 'callName3':callName() };
var obj2 = {'callName4':callName(), 'callName5':callName() };
//test out the tattle-tale function:
obj1.callName2(); // alerts 'callName2'
obj2.callName5(); // alerts 'callName5'
if you REALLY want to make it look like an assignment and avoid the execution parens each time in the object literal, you can do this hacky routine to create an invoking alias:
function callName() {
return function callMe(){
for(var it in this) if(this[it]===callMe) return alert(it);
}
};
//make an alias to execute a function each time it's used :
Object.defineProperty(window, 'callNamer', {get: function(){ return callName() }});
//use the alias to assign a tattle-tale function (look ma, no parens!):
var obj1 = {'callName2': callNamer, 'callName3': callNamer };
var obj2 = {'callName4': callNamer, 'callName5': callNamer };
//try it out:
obj1.callName2(); // alerts 'callName2'
obj2.callName5(); // alerts 'callName5'
all that aside, you can probably accomplish what you need to do without all the looping required by this approach.
Advantages:
works on globals or object properties
requires no repetitive key/name passing
uses no proprietary or deprecated features
does not use arguments or closure
surrounding code executes faster (optimized) than
a try/catch version
is not confused by repeated uses
can handle new and deleted (renamed) properties
Caveats:
doesn't work on private vars, which have no property name
partially loops owner object each access
slower computation than a memorized property or code-time repetition
won't survive call/bind/apply
wont survive a setTimeout without bind() or a wrapper function
cannot easily be cloned
honestly, i think all the ways of accomplishing this task are "less than ideal", to be polite, and i would recommend you just bite the coding bullet and pass extra key names, or automate that by using a method to add properties to a blank object instead of coding it all in an object literal.
Yes.
Sort Of.
It depends on the browser. (Chrome=OK, Firefox=Nope)
You can use a factory to create the function, and a call stack parsing hack that will probably get me arrested.
This solution works in my version of Chrome on Windows 7, but the approach could be adapted to other browsers (if they support stack and show the property name in the call stack like Chrome does). I would not recommend doing this in production code as it is a pretty brittle hack; instead improve the architecture of your program so that you do not need to rely on knowing the name of the calling property. You didn't post details about your problem domain so this is just a fun little thought experiment; to wit:
JSFiddle demo: http://jsfiddle.net/tv9m36fr/
Runnable snippet: (scroll down and click Run code snippet)
function getCallerName(ex) {
// parse the call stack to find name of caller; assumes called from object property
// todo: replace with regex (left as exercise for the reader)
// this works in chrome on win7. other browsers may format differently(?) but not tested.
// easy enough to extend this concept to be browser-specific if rules are known.
// this is only for educational purposes; I would not do this in production code.
var stack = ex.stack.toString();
var idx = stack.indexOf('\n');
var lines = ex.stack.substring(idx + 1);
var objectSentinel = 'Object.';
idx = lines.indexOf(objectSentinel);
var line = lines.substring(idx + objectSentinel.length);
idx = line.indexOf(' ');
var callerName = line.substring(0, idx);
return callerName;
}
var Factory = {
getFunction: function () {
return function () {
var callName = "";
try {
throw up; // you don't *have* to throw to get stack trace, but it's more fun!
} catch (ex) {
callName = getCallerName(ex);
}
alert(callName);
};
}
}
var obj1 = {
'callName2': Factory.getFunction(),
'callName3': Factory.getFunction()
};
var obj2 = {
'callName4': Factory.getFunction(),
'callName5': Factory.getFunction()
};
obj1.callName2(); // should alert 'callName2'
obj1.callName3(); // should alert 'callName3'
obj2.callName4(); // should alert 'callName4'
obj2.callName5(); // should alert 'callName5'
In namespace we can use something like this:
var namespace = {};
namespace.something.nested.namespacing();
And also in prototype we can use same like name the namespace:
something.prototype.method();
In both types we are using . notation. So, how can we determine the code is using namespace or prototype?
JavaScript doesn't have namespaces. What you're calling a namespace is just an object. It's fairly common to use objects to stand in for namespaces.
Your code:
var namespace = {};
namespace.something.nested.namespacing();
...creates an object and a variable that refers to that object called namespace. Then you add properties to that object (it looks like you've added a property, something, which is also an object, which has a property, nested, which is also an object, which has a property called namespacing which refers to a function).
Your code:
something.prototype.method();
...is also using an object. The above would actually be a really unusual thing to do, you're calling a function (method) by directly referring to the prototype property of what I assume is a function (something). That's not normally what you would do. Normally you'd create an object via the function:
var s = new something();
...and then use the prototype that got assigned to s implicitly:
s.method();
The prototype property on functions can be confusing to people new to JavaScript. It's just a normal property like any other property, which is on function instances. The only thing that makes it special is the new operator: When you call a function via new:
var s = new something();
...the JavaScript engine creates a new, blank, object, then sets its underlying prototype (sometimes called __proto__ but that's not in the spec [yet]) using something.prototype, like this:
// pseudo-code for `var s = new something()`
var tmp = {}; // New, blank object
tmp.__proto__ = something.prototype; // Assign a prototype to the new object
something.call(tmp); // Call `something` with `this` referring to `tmp`
s = tmp; // Assign the result to `s`
(There's a detail I left out in the above to avoid confusing matters, to do with the special case where something has an explicit return statement in it that returns an object reference.)
Well, namespaces are just objects and prototype objects are objects, so from a syntactic point of view, there is no difference how you access them (foo.bar is called dot notation().
However, they serve two fundamentally different purposes:
Namespaces are used to structure your code and to avoid global namespace pollution.
Prototypes are used to share methods between multiple instances of the same constructor function.
So you usually don't call a method directly on the prototype because it most likely won't work. The purpose of this method is to be called on an instance of the corresponding constructor function. For example:
function Something() {}
Something.prototype.foo = function() {};
var s = new Something();
s.foo();
The . notation is a very general purpose tool used in javascript for accessing any properties of any object.
var x = {};
x.val = 2;
Your reference to a namespace is just a general purpose object in javascript as there is no actual namespace type in javascript. In other words, plain objects are used to create namespace-like things in javascript. So, as such, object properties are used to keep track of names in the namespace.
The . notation's use with the prototype is one specific instance of accessing properties on a specific type of object (the prototype). A prototype is used on a function object and has a very specific use when creating new instances of that function.
function foo() {
}
foo.prototype.talk = function() {
alert("hello");
}
var y = new foo();
y.talk();
I definitely need some light on this.
What's the diference between:
var MY_APP = function(){
this.firstMethod = function(){
//something
};
this.secondMethod = function(){
//something
};
};
and
var MY_APP = {
firstKey: function(){
//something
},
secondKey: function(){
//something
}
};
besides the obvious fact that one is a Function and the other an Object, what are the differences in code flow, prototypes, patterns... whatever, and when should we use the first or the second?
I'm so spaced out in this area that i'm not sure if i'm correctly explaining the doubt, but further info can be given if you ask.
The key difference between the two is in how they are intended to be used. A constructor, as its name suggests, is designed to create and set up multiple instances of an object. An object literal on the other hand is one-off, like string and number literals, and used more often as configuration objects or global singletons (e.g. for namespacing).
There are a few subtleties about the first example to note:
When the code is executed, an anonymous function is created and assigned to MY_APP, but nothing else happens. firstMethod and secondMethod don't exist until MY_APP is explicitly called.
Depending on how MY_APP is called, the methods firstMethod and secondMethod will end up in different places:
MY_APP(): Since no context is supplied, the this defaults to window and the methods will become global.
var app1 = new MY_APP(): Due to the new keyword, a new object is created and becomes the default context. this refers to the new object, and the methods will get assigned to the new object, which subsequently gets assigned to app1. However, MY_APP.firstMethod remains undefined.
MY_APP.call(YOUR_APP): This calls my MY_APP but sets the context to be another object, YOUR_APP. The methods will get assigned to YOUR_APP, overriding any properties of YOUR_APP with the same names. This is a really flexible method that allows multiple inheritance or mixins in Javascript.
Constructors also allow another level of flexibility since functions provide closures, while object literals do not. If for example firstMethod and secondMethod rely on a common variable password that is private to the object (cannot be accessed outside the constructor), this can be achieved very simply by doing:
var MY_APP = function(){
var password = "GFHSFG";
this.firstMethod = function(){
// Do something with password
alert(password); // Woops!
};
this.secondMethod = function(){
// Do something else with password
};
};
MY_APP();
alert(password); // undefined
alert(MY_APP.password); // undefined
The first is a function, the second is an object literal. Since Functions in JS are first class objects, a function can have properties on it, just like any other object can.
Typically, if you want to create a "class" that you might be familiar with from classical inheritance languages, you would do something like
function MyClass() {...}
as is documented here http://www.crockford.com/javascript/inheritance.html
To answer the question posed in your edits, you would use them both in different situations. Object literals are used to pass configurations around. A typical usage pattern would be a method that accepts an object literal like so
something.init({
length: 10,
height: 10,
text: 'some text'
});
and so on.
You could use something similar to your first example when creating a namespace. Javascript has some interesting language features in that you can have so-called "self-invoking functions" that are of the form:
var myApp = (function(){
var firstMethod = function() {...}
...
})();
the motivations behind doing something like this are detailed here
http://sparecycles.wordpress.com/2008/06/29/advanced-javascript/
You can also investigate the differences via your favorite javascript debugging console. In firebug and chrome, I did the following:
var ol = {}; ol.prototype;
var fn = function(){}; fn.prototype;
the first line prints undefined, the second returns a prototype with a constructor of 'function'
The constructor can be reused as is, the object literal would need to be repeated or wrapped in a function to be reused.
Example of wrapping the object literal in a function:
function MY_APP() {
return {
firstKey: function(){
//something
},
secondKey: function(){
//something
}
};
}
The object created using the constructor will have it's constructor property set to the constructor function. However, as you used an anonymous function assigned to a variable instead of a named function, the constructor will still be nameless.
Other than that, there isn't really any differences. Both create anonymous functions that are assigned to the properties of the object, so the resulting objects are the same. You can compare this to assigning named functions to the properties, or using prototype functions, both having the difference that each function only exists once instead of being created over and over for each object.
There is some confusion in JavaScript regarding the difference between a function and an object.
In the first case,
var MY_APP = function() { this.v = 7; ... }
or
function MY_APP(x) { this.v = x; ... }
a function is declared, not an object. In MY_APP, this refers to the global object.
Meaning that calling the function MY_APP(7) will assign v globally to the value of 7. (and in your case the function firstMethod would be declared globally).
MY_APP(3); // The global variable v is set to 3
MY_APP(4); // The global variable v is overwritten and set to 4
To use MY_APP as an object, it needs to be instantiated, for instance
var obj1 = new MY_APP(3);
var obj2 = new MY_APP(4);
will have obj1.v to be 3, and obj2.v to be 4.
Note you can also add methods using the prototype keyword (instead of this.firstMethod...)
MY_APP.prototype.firstMethod = function () { ... }
In the second case
var MY_APP = { ... };
an object, one object, is created and its name is MY_APP. The this keywords refers to that object, MY_APP.
When i started learning function in C++ its all around pass by value and reference.
Is there something similar we have in javascript ?
If yes/not how it works in case of javascript?
Thanks all.
Other answers to this question are correct - all variables are passed by value in JavaScript, and sometimes that value points to an object.
When a programming language supports passing by reference, it's possible to change where the variable points from inside a function. This is never possible in JavaScript.
For example, consider this code which attempts to reassign the passed variable to a new value:
function changeCaller( x ) {
x = "bar"; // Ha ha!
}
function testChangeCaller() {
var x = "foo";
changeCaller(x);
alert(x); // still "foo"
}
testChangeCaller();
Attempts to point variables at new objects fails in the same way the above example fails to reassign a primitive string:
function changeCaller( x ) {
x = new Object(); // no longer pointing to the same object
x.a = "bar";
}
function testChangeCaller() {
var x = new Object();
x.a = "foo";
changeCaller(x);
alert(x.a); // still "foo"
}
testChangeCaller();
The feature which leads people to believe they're dealing with a pass-by-reference scenario is when modifying objects. You can make changes to an object or array, because the local variable points to the same object:
function changeCaller( x ) {
x.a = "bar";
}
function testChangeCaller() {
var x = new Object();
x.a = "foo";
changeCaller(x);
alert(x.a); // now "bar", since changeCaller worked on the same object
}
testChangeCaller();
Hope this helps!
JavaScript is always pass by value, never pass by reference. A lot of people confuse this because of the way objects work.
There is no "pass by reference" for any variable in JavaScript (no, not even if an object is assigned to that variable). All variables and arguments are assigned by value. If the assigned value is an object, then the value of the new variable is a reference to that object, but assigning a new value/object to the new variable will not affect the original variable.
Some people term this behaviour passing "value by reference".
A comparison - PHP
$foo = "foo";
$bar = &$foo; // assign by reference
$bar = "bar";
echo $foo; // -> output: "bar"
JavaScript
foo = {"foo": true};
bar = foo; // assign value by reference
bar = {"bar": true};
alert(JSON.stringify(foo)); // -> output: '{"foo": true}
Regard the discussion, the considerations about "value" and "reference" are wrong on the exception of the Pointy comment.
Javascript like other reference laguages like c# or java, don't pass a referece to the variable itself to the method, but the reference of the object referenced by the variable.
What the people here is expecting, is passing a pointer to the variable which is referencing the object, pass by pointer is not the same as pass by reference, and sure is not the same as pass by value.
The behavior expected here is pass by pointer.
Pass by reference sends the reference to the object.
Pass by value copy the object stored in the variable and pass the copy
to the method.
The pass by value, pass by reference discussion is an evil meme. This evil meme crops up in Java discussions too.
It's simple: The bit pattern of the value is copied to the parameter. It doesn't matter if the bit pattern is an int or if it's the address of an object -- it's just copied, bit by bit, into the parameter. It couldn't be simpler. The run-time isn't doing something special for primitives versus references. It simply, and always, just makes a copy of the value.
The computer science term for this is "pass by value."
Pass by reference just isn't used in programming any more. In older languages, like Pascal, you could code a function to directly alter the value in the calling routine. So, for example, an int variable in the calling routine could be altered in the called function.
Primitive values are passed via value and objects are passed via reference.
Strings are immutable, so they are passed via reference although they are considered as primitive type.