Working of Date in Javascript - javascript

I recently learned that we can't access inner function directly. We need to make the object of the function to do that. However it looks different to me in Date function since we can access inner functions like Date.now().typeof Date returns "function" and not "Object".
What am I missing here?

You can make a such thing. Here b function is a function of the A.
Typeof A will return function. But in Javascript functions are also objects. So you can add properties and functions(methods) to the function object itself.
function A(){
}
A.b = function(){
console.log('B');
}
A.b();
But if you mean inner function to this
function A(){
function b(){
console.log('b') ;
}
}
You can't access the inner b function outside the A .
One case to access the inner function outside the A, you need to assign the function to the this, which is called method, then create an object of A and use that method.
function A(){
this.b = function (){
console.log('b');
};
}
let a = new A();
a.b();

Actually, Date is the constructor of the Object Date,
so it is a common sense that you use new Date() to get access into these 'inner functions' you referred in your question:
type of Date // function
type of Date() // string, shorthand of new Date().toString()
type of new Date() // object

The inner function mostly is a constructor Function.
e.g:
function MyDate () {
}
MyDate.prototype.getDate = function () {
console.log('getDate')
}
MyDate.getDate() // getDate

Related

What is the different between var myFunc = new Object(function myFunc () {}) and function myFunc () {}?

I didn't know you could create a function using new Object:
var myFunc = new Object(function myFunc () {})
Looking at the console, it seems identical to:
function myFunc () {}
Is there a reason to use new Object to create a function?
According to the Object(...) documentation:
The Object constructor creates an object wrapper for the given value. If the value is null or undefined, it will create and return an empty object, otherwise, it will return an object of a Type that corresponds to the given value. If the value is an object already, it will return the value.
Functions are objects, therefore it will just return the function. The new Object(...) part is a no-op. So the code is basically just:
var myFunc = function myFunc() { }
and that is barely equal to a function declaration

Am I passing an object to object.defineProperties?

I am learning javascript and would love help understanding the snippet of code.
From Object.DefineProperties definition, the first parameter is an object. Is MyObjectConstructor a declaration or an object. With a constructor function I would expect to call new to make it an object.
This is what is confusing me. Or as I read in Javascript functions are objects so do I treat it as an object and the this property is where all staticProps and instanceProps are added to?
var _prototypeProperties = function (child, staticProps, instanceProps) {
if (staticProps){
Object.defineProperties(child, staticProps)
};
if (instanceProps) {
Object.defineProperties(child.prototype, instanceProps);
}
};
function myFunction() {
function MyObjectConstructor(element) {
this.element = element;
this.initialized = false;
}
_prototypeProperties(MyObjectConstructor, {...}, {...});
}
Yes, (constructor) functions are objects as well in javascript, and you can add properties directly to them.
The _prototypeProperties function in your example snippet does put the staticProperties on the constructor, so that they could be accessed as MyObjectConstructor.myStaticProperty. It also does put instanceProps (better: "class properties", "prototype properties") on the MyObjectConstructor.prototype object, from where they are inherited by instances: (new MyObjectConstructor).myPrototypeProperty. Lastly, your MyObjectConstructor does put "real" (own) properties on the instances, specifically (new MyObjectConstructor).element and .initialised.
In JavaScript, once defined, the resulting functions act identically:
function Hat() { }
var Hat = function() { }
Conventionally the first is used to create objects (usually with new) and the second is used as a regular method.
The new operator, when preceding a function gets kinda weird. Using the new operator will:
create a new Object "it"
set the function being called as "it"s prototype
binds "it" to this within the function
overrides the return value of the function with "it". This overrides both explicit returns and implicit returns of undefined.
For example:
// first define Hat function
function Hat() { this.color = 'red' }
// calling with `new` implicitly returns a new object bound to the function
new Hat()
// > Hat { color: "red" }
// invoking without `new` implicitly returns `unefined`,
// but `this` points to Hat's parent object.
// If running in the browser, Hat's parent object would be `window`
// so now Window.color is set to "red"
Hat()
//> undefined
Window.color
//> "red"
Be careful with new, because the new object will be returned instead of any explicit returns.
var color = function() { return "blue" }
color()
//> "blue"
new color()
//> color {}
JavaScript is prototypal by nature. The new operator reflects neither prototypical nor classical inheritance. I avoid it when possible, although many popular libraries use it.
I recommend reading through Crockford's explanation of JavaScript's prototypal inheritance: http://javascript.crockford.com/prototypal.html
Its terse, but if you understand his 10 lines of demo code you'll be good.
Play with bind, call and apply, and different scoping contexts too. After understanding scoping and the prototypal nature, the rest is just syntax.
first : the function is the first type object in the javascript . it means you can deliver the function as value . for example :
function test(){
return function(){
console.log('function');
}
}
test()();
you return the function as return an object , function can be assigned and the function another kind of value !
var test = function(i) {
// body...
return i;
}
test('123');
a character string 'test' refer to a Anonymous function , you can understand that you transmit a function to a character string .
second : if you use new to create a instance via function , this function will be called construction function , normally it used to init the params , and the instance will take the construction function own property or method and prototype's property or method from the construction function .
third : the instance's property of "__proto__" is refer to the construction function's prototype object . this is why the instance can use the prototype's property or method from the construction function .
forth : if you create the instance by new , the this will refer to the instance object ! so that instance can use the property and method .
from your code :
var _prototypeProperties = function (child, staticProps, instanceProps) {
if (staticProps){
Object.defineProperties(child, staticProps)
};
// the properties from the own construction function , like this :
// this.element = element;
// this.initialized = false;
if (instanceProps) {
Object.defineProperties(child.prototype, instanceProps);
}
};
// the properties from the construction function's prototype object . like this :
// MyObjectConstructor.prototype.name = 'somebody';
// MyObjectConstructor.prototype.getName = function(){
// return this.name;
// }

Call javascript dynamic method in object

If I create a Class with two method like following:
var Car = function() {}
Car.prototype = {
run: function() {
alert('run');
},
stop: function() {
alert('stop');
}
}
And when the DOM is ready will call test() method,
and this test() method will create a instance of Car and call the method of Car
$(document).ready(function() {
test("run");
});
function test(method) {
var instance = new Car();
// call instance.run()
}
I know I have to use apply() method,
but I have tried lots of times and failed
So, how can I use apply() method in Object?
An object in javascript is an associative array, so you can use the [] operator to address by string any member of the object, functions as well.
function test(method) {
var instance = new Car();
instance[method]();
}
this will allow to call a function by name over the object Car.
See it working on JsFiddle.
The context inside the called method will properly point to the newly created Car instance without any additional effort, that I guess is what you want. Using apply or call is generally used when you need to change the default 'this' value to something else.
I know I have to use apply() method,
You don't. Uncomment the instance.run() code, call the test() method and it works.
demo: http://jsfiddle.net/JkAnb/
how can I use apply() method in Object
It depends on what you want to achieve. There is documentation at MDN.
perhaps you want to call
instance.method()
call dynamically i.e. based on value passed run/stop. You can try this -
instance[method].call(instance)
or
instance[method].apply(instance)
where instance is passed as scope param which is scope of the function to be called (value of "this" inside function).
Why do You need classes in an (object based) functional language?
Your intent is bit unclear. What is the implied type of the argument 'method' in Your test function?
I assume it is a method name. In any case code bellow might help.
/* prefer this class pattern */
var Car = (function () {
"use strict";
Car.prototype = {
name : undefined ,
run: function () {
return name_ + ":: run";
},
stop: function () {
return name_ + ":: stop";
}
};
/* constructor */
function Car(name) {
name_ = name;
}
return Car;
})();
function printer(msg_) {
document.body.innerHTML += msg_ + "<br/>";
}
function test(car_, method_name_1, method_name_2) {
printer(car_[method_name_1]());
printer(car_[method_name_2]());
}
test( new Car("BMW"), "run", "stop");
test( new Car("Lada"), "run", "stop")
in addition, you could also use the eval function:
var instance = new Car();
eval('instance.'+method+'();');
though Felice Pollano's way is far neater imo.
http://jsfiddle.net/VZdXb/

JavaScript return method

I'am new in javascript.
I can't understand why the function returns T1 object (not just string 'hi') in the following example.
function T1(){
return 'hi';
}
function T(){
return new T1();
}
T();
output: T1
And returns function in the following example
function T1(){
return function(){ return 'hi'; }
}
function T(){
return new T1();
}
T();
output: function (){ return 'hi' }
Why does the first example returns an object (not the string "hi", what is expected to happen) and the second returns the function body that is returned from the first function (not the expected object)?
Please explain this result. Thank you)
The new operator returns the object created by the operator unless the constructor function returns a different object. Any non-object return value of the constructor function is ignored, which is why when you return hi you don't see this.
Section 13.2.2 ("[[Construct]]") of the specification, which is referenced by Section 11.2.2 ("The new operator").
The new keyword. That makes an object.
function T1(){
return 'hi';
}
function T(){
return T1();
}
T(); // 'hi'
JavaScript objects should be like this:
function T1(){
this.test = function(){
return 'hi';
};
}
function T(){
return new T1();
}
var test = T(); // T1 object
test.test(); // 'hi'
In your code:
> function T1() {
> return 'hi';
> }
A function called as a constructor will always return an object, it won't return a string. So when called simply as a function, T1 will return the string 'hi', but when called as a constructor, it iwll return a new T1 instance. Since that instance isn't assigned any properties, nor does T1.prototype seem to have any, it will be almost indistinguishable from an object created using new Object().
It will be an instanceof T1 and its constructor property will reference T1.
> function T() {
> return new T1();
> }
By convention, only constructors start with a capital letter (except for constants, which might be all capitals).
> T();
The T function simply returns a new T1 object, which is not assigned to anything so can't be referenced or called, so it's immediately available for garbage collection. It has not special methods or properties.
var t = T(); // returns a new T1 instance
t(); // throws an error since t is a plain object,
// not a function and so can't be called.
Edit
Since the question was changed:
function T1() {
return function(){ return 'hi'; }
}
In this case, when T1 is called as a constructor, the return statement returns a function, which is an Object (all functions are objects), so that is what is returned.
The function is returned in the second example because you returned an anonimous function on T1() and so, you can execute it placing a pair of parentesis () in front of if:
function T1(){
return function(){ return 'hi'; }
}
function T(){
return new T1();
}
T()(); // hi
// or
var T2 = T();
T2(); // hi
This is not a bug, its a powerfull feature from JS.
Just remember of "Spiderman" frase:
With great powers cames great responsabilities.
Edit:
Now I see the real question: Why does the first example returns an object (not the string "hi", what is expected to happen) and the second returns the function body that is returned from the first function (not the expected object)?
This seems a bug to me, but maybe by design, since functions and objects returned can be used and a workaroud with a parameter is easy to do.

object issues of javascript

I constructed a function defined as
var Func1 = function()
{
return {
alert: function() { alert( "Lady Gaga" ); }
};
};
And I assigned Func1() to a variable, like this:
var func1 = Func1();
I found something make no sense to me that Func1() created an object for func1 although I didn't put the new in front of it.
Isn't that objects could only be created by new?
What happened when the expression above is being executed?
JavaScript doesn't need the new keyword. The above code assigned the return value to the newly created func1 variable.
When you write a javascript literal object (json like), it's the equivalent to create a new object with the new operator and assign its properties.
This
var a = { test: 123, caca: 'pipi' };
Is the same as
var a = new Object();
a.test = 123;
a.caca = 'pipi';
Look at what you are returning from Func1:
return {
alert: function() { alert( "Lady Gaga" ); }
};
You return an object, and that object is assigned to func1. So func1 = Func1(); simply calls Func1, and assigns the result of that to func1.
Your function is creating an object with:
{
alert: function() { alert( "Lady Gaga" ); }
};
Using that notation, there's no need to use the new operator.
The () actually executes the function, which returns an object with a method (a method is a property of type function).
In JS, you don't explicitly call new to create new objects:
var song = {
name: "Entrenched",
artist: "Morbid Angel"
};
song.artist = "Bolt Thrower";
This creates an object with the properties name and artist.
The new keyword used with a function is one way to create an object, but not the only way. It means that a new object will be created with the specified function called as a constructor - within the constructor the this keyword will reference the new object, and the new object will be returned. Call the same function without the new keyword and an object will not be created.
The object literal syntax (e.g., var x = { }; or return { };) is another way to create an object.

Categories

Resources