How to output call object in javascript? - javascript

while I was reading a javascript book, I read the following sentence.
"The call object is initialized with a property named arguments that refers to the Arguments object for the function"
am I allow to output the structure (or values?) of a call object in javascript using console.log or alert() method??
when people say 'a call object', is it a concept or an object?

The "call object" is referred to as an "activation object" in the ECMAScript specs, and it cannot be accessed directly. This allows ECMAScript/JavaScript engines to implement it in an optimal way because they only have to ensure that it always behaves correctly, even if there's not literally an object with argument property, properties for variables, etc.
Here's the description from the spec (with emphesis added):
10.1.6 Activation Object
When control enters an execution context for
function code, an object called the
activation object is created and
associated with the execution context.
The activation object is initialised
with a property with name arguments
and attributes { DontDelete }. The
initial value of this property is the
arguments object described below.
The activation object is then used as
the variable object for the purposes
of variable instantiation.
The activation object is purely a
specification mechanism. It is
impossible for an ECMAScript program
to access the activation object. It
can access members of the activation
object, but not the activation object
itself. When the call operation is
applied to a Reference value whose
base object is an activation object,
null is used as the this value of the
call.

I believe they are referring to the object calling the method/function.
This can be referenced by the this keyword
<a onclick="foo()">click me</a>
function foo(){
this.style.color='#cc0000';
alert(arguments.length);
}
This code would change the text color of the anchor to '#cc0000' and alert 0.

Related

Window object properties behavior

When we have normal javascript objects, we can access there properties by using a syntax like objectName.proprtyName. If we just use propertyName only, then we will get an error as below -
const myObj = {
userIdName : "John"
};
console.log(myObj.userIdName); //John
console.log(userIdName); //error "Not defined"
However, in the case of in-built window object, we can use both window.propertyName and propertyName alone as below -
console.log(window.alert);
console.log(alert);
//both return same result
What exactly is responsible for this behavior of the window object? Can we replicate the same behavior for any explicitly built object like the object in the first snippet? (Although nobody would want to pollute the global scope, but I just have this query)
Edit - I have received comment that this question is a duplicate of another question. This question is very much similar to my answer except one difference - I am looking for a way to replicate the same globally accessible behavior of the window object.
What exactly is responsible for this behavior of the window object?
JavaScript has two major types of environment records (a construct to "hold" name -> value associations): a declarative record and an object record.
A declarative environment record stores those association in an implementation specific manner. This is the most common type of environment record and is created when you call a function for example.
An object environment record uses, as indicated by the name, an actual JavaScript object as the "backend". That means every entry in that environment becomes a property of that "binding object" and vice versa.
The global environment uses such an object environment and that binding object is available via window in browsers.
Can we replicate the same behavior for any explicitly built object like the object in the first snippet?
It is possible with the deprecated with statement still exists and creates an object environment record using the provided object as a binding object. From the spec:
The with statement adds an object Environment Record for a computed object to the lexical environment of the running execution context. It then executes a statement using this augmented lexical environment. Finally, it restores the original lexical environment.
var obj = {foo: 42};
with (obj) {
console.log(foo);
}

What are virtual functions in javascript?

According to one definition of virtual functions:
In object-oriented programming, in languages such as C++, a virtual
function or virtual method is an inheritable and overridable function
or method for which dynamic dispatch is facilitated.
How would this look for functions in javascript?
How would this look for functions in javascript?
The concept largely doesn't apply to JavaScript.
The concept of virtual and non-virtual functions (methods, really) requires the concept of a type of reference to an object, as distinct from what the object is. For instance, you might have a BaseFoo type with a bar method, and a DerivedFoo type that derives from it and overrides bar. Later, if you have a BaseFoo-typed variable b referring to a DerivedFoo object, when you call b.bar(), you'll get DerivedFoo's bar if bar is virtual, but BaseFoo's bar if bar is non-virtual. But if you have a DerivedFoo-typed variable d referring to a DerivedFoo object, d.bar() always calls bar whether it's virtual or not. The type of the variable you're using to refer to the object determines what method gets called if the method is non-virtual.
None of that exists in JavaScript. References to objects are untyped. When you call o.bar(), you get the property bar from that object and call the function it refers to.
If you wanted to stretch a point, given JavaScript's prototypical inheritance mechanism, you could say that in some sense, all JavaScript "methods" are virtual, if we very loosely say a "method" is a function attached to an object property (although in ES2015+, "method" has a more specific meaning in JavaScript than that, but still fits that definition). That's because when you look up a property on an object, if it has its own property with that name, that's the one you get; you only get the one from its prototype if it doesn't have its own. But that's probably stretching a point, perhaps too far.

Why do Function properties are defined on the object itself (e.g. Function.name), but methods - on Function.prototype?

From the API properties are defined like Function.name, and methods like Function.prototype.call(). But in the code I still invoke them in the same way, for example:
function Foo() {console.log("inside Foo")}
console.log(Foo.name); // Foo
Foo.call(); // inside Foo
I.e. I simply put a function name(Foo), then a method/property I want to use. Then why in API do I see properties defined on Function, and methods - on Function.prototype ?
Placing methods in the prototype allows you to share them among all instances, instead of duplicating them for each one.
For example, the behavior of Function.prototype.call does not depend on which function is called. It only needs a reference to the function (received via this argument) in order to call it later.
However, intrinsic data like name must be stored in the function object itself. It can't be stored in the prototype because each function instance has its own name. Well, it could be store as an internal [[Name]] property, and accessed via a getter and setter defined in the prototype, but the data would still need to be stored in the function.
Note there are non-method properties defined in the prototype, e.g. constructor.
Short answer:
Functions (in general) can be shared among instances, so they go in prototype.
Properties are per-instance, so go in the constructor.
prototype properties (such as the method Foo.prototype.call) are accessible using instances of the object, while direct properties (such as Foo.name) are accessible through the object itself (and not its instances) like static properties.
In your example there is a big difference between Foo.name and Foo.prototype.call, in order to use Foo.name you can call it directly, while in order to use Foo.prototype.call - you need to create an instance, and then it'll be available
function Foo(){}
Foo.prototype.call = funciton(){console.log('I was called');}
Foo.name = 'My name is';
console.log(Foo.name); //My name is
var instance = new Foo();
instances.call(); //I was called
Another thing you need to notice is that both name and call has a native definition in the Function object type in JavaScript - therefore when you call Foo.call() - you call the Function.prototype.call method (which is just like calling Foo();, with one small difference that doesn't affect in this case)
There are actually some argument for placing the default values of immutable values (or objects that are not mutated, by contract) in the prototype for common/expected properties.
Re-assignment of the properties will always be in the 'current this' object (well, object on which the assignment occurs). So if properties are assigned later - in the constructor or even after that - they will be 'promoted' to properties of the actual instance and not the prototype1.
However, since the difference (if any) is very modest, and dependent upon situation, it is common practice just to dump all the property assignments in the constructor. Per-object properties would need to be set individually anyway, regardless of the approach used.
Sharing mutable properties in the [prototype] can get questionable as then the property (when mutated) acts akin to a static variable; mutating shared objects should always be done with care.
1 The only observable difference as to 'where' default properties are assigned is if hasOwnProperty is used.
Interesting related-ish read: Should I put default values of attributes on the prototype to save space? (And yes, I know this disagrees with my vary first sentence.)
You have a slight misconception here. You can define properties and functions (methods) on the function itself. You can define properties and functions that you want the object that the function construct on the prototype. It's not the same thing.
For example, the .create() method of the base Object constructor is defined as as Object.create() but the .hasOwnProperty() method of object instances is defined as Object.prototype.hasOwnProperty().
For example, if you have an object mango created from the constructor Fruit() then:
mango.weight(); // method comes from Fruit.prototype.weight()
Fruit.isFruit(mango); // method comes from Fruit.isFruit()
In particular, the this inside Fruit.isFruit() refers to the function Fruit() while the this inside Fruit.prototype.weight() in the above example refers to the object mango.
If you are used to OO programming from other languages, the difference is between static and non-static class members.

What version of javascript introduced arbitrary constructor return?

Someone in the question Is there any reason to manually return in a constructor function mentioned that he thought that returning arbitrary objects in constructor calls may have been introduced in a recent version of Javascript.
I am unable to access alternate browsers right now, and I can't find any information about this, so what version introduced this, or has it existed since forever?
If it hasn't been around for long, then what browser versions will support it?
If you look in ECMA-262 ed 1 (which is still available online from the ECMA site) you will see:
11.2.2 The new operator
The production NewExpression : new NewExpression is evaluated as follows:
Evaluate NewExpression.
Call GetValue(Result(1)).
If Type(Result(2)) is not Object, generate a runtime error.
If Result(2) does not implement the internal [[Construct]] method, generate a runtime error.
Call the [[Construct]] method on Result(2), providing no arguments (that is, an empty list of arguments).
If Type(Result(5)) is not Object, generate a runtime error.
Return Result(5).
And then in §15.3.2.1 #18 the [[Construct]] method is explained (in the following, F is a newly constructed Function object):
18. Set the [[Construct]] property of F to a method that, when it is invoked, constructs a new object whose [[Prototype]] property is equal
to the value of F.prototype at the time the [[Construct]] method is
invoked (but if this value is not an object then the value of
Object.prototype is used), then invokes F as a function (using its
[[Call]] property) with the new object as the this value and the
arguments given to the [[Construct]] method as the arguments. If the
result of invoking the [[Call]] method is an object, that object
becomes the result of the invocation of the [[Construct]] method;
otherwise the new object becomes the result of the invocation of the
[[Construct]] method.
So a constructor returning this by default has been in ECMAScript since the beginning.
There are several reasons to return manually in the constructor function. Singleton is just one of them.
Constructors are just functions that are meant to be used with the new operator. When invoked in such a way, this would get bound to a an object that is created based on that function's prototype. That this is also the one that is returned when you invoke that function using new (or is bound to window if you don't use new).
this is a slight simplification of the process, but that should give a good overview
When you explicitly return an Object from such a constructor function - the original object that was created using that function's prototype is discarded and the explicit one is returned (as one would expect).
As far as I know it was always like this - or at least for as long as functions were allowed to return a value. :)
Here is a link:
From ECMA-262 3rd edition LS-like(1999 - so yeah, almost forever:)

Activation and Variable Object in JavaScript?

Is the term "activation object" just another name of "variable object" or is there actually any difference between them? I have been reading a few JavaScript articles about how variable scopes are formed in an execution context, and from my point of view it seems that in most of the articles they use these two terms interchangeably.
Well, I just learned something :). From this article, it would appear that within the execution context of a function, the Activation Object is used as the Variable Object:
When an execution context is created a number of things happen in a defined order. First, in the execution context of a function, an "Activation" object is created. [...]
Then the process of "variable instantiation" takes place using an object that ECMA 262 refers to as the "Variable" object. However, the Activation object is used as the Variable object (note this, it is important: they are the same object). Named properties of the Variable object are created for each of the function's formal parameters, and if arguments to the function call correspond with those parameters the values of those arguments are assigned to the properties (otherwise the assigned value is undefined).
However, when you're in the global scope, there isn't an Activation Object, so the Global Object is used as the Variable Object instead:
The global execution context gets some slightly different handling as it does not have arguments so it does not need a defined Activation object to refer to them. [...] The global object is used as the Variable object, which is why globally declared functions become properties of the global object.
So it sounds like "Activation Object" and "Variable Object" are the same thing within a function context, but not within the global context.
An activation object is the uppermost object in a scope-chain with the lowermost being global object.
Whereas variable object is abstract concept and therefore, depending on its execution context, is any link in scope-chain including activation/global object.
It contains:
all the variables and functions you declare inside the function body;
arguments named as specified by the function signature;
arguments as an object named arguments (in case you want your function to support multiple signatures).
It doesn't contain:
this (as it's not a variable);
named function expressions.
Further info - JavaScript. The core.
Few quotes in case of tl;dr:
A variable object is a scope of data related with the execution context. It’s a special object associated with the context and which stores variables and function declarations are being defined within the context.
A variable object is an abstract concept. In different context types, physically, it’s presented using different object.
[..] in the global context the variable object is the global object itself [..]
[..] a function’s variable object is the same simple variable object, but besides variables and function declarations, it also stores formal parameters and arguments object, and is called the activation object.
[..] when accessing this in a code, its value is taken directly from the execution context without any scope-chain lookup.
It's more accurate to say that an Activation object is a type of Variable object. This is similar to how a man is a type of HUMAN. As stated here, the term 'Variable object' is just a GENERALISED term used to describe any object that holds the properties that describe the environment and scope of the currently executing context.
Hence, within the global executing context (i.e., outside of any functions), it ends up being the Global object. Why? Because it’s the object that holds the properties that describe the environment and scope of the global executing context.
Whereas within the function local executing context (i.e., within a function), it is the function local object (a.k.a the Activation object) that is the Variable object, as it's the object that holds the properties that describe the environment and scope of the currently executing function. Properties such as function arguments for example.
An activated object just means an object that represents an element on a web page that an event occurred on. So if an image is clicked, the JavaScript object that represents that image is the activated object.

Categories

Resources