TypeError: this is not a Date object

Any idea why this is not working in Chrome?
var foo = (new Date).getDate;
foo();

I get a TypeError: this is not a Date object. However (new Date).getDate() works

+4
source share
5 answers

In JavaScript, the this context is not bound to every object method. Rather, it is defined at runtime as you call this method Check this answer to learn more about binding behavior. .

In your code, foo gets the getDate new Date property, which it gets from Date.prototype through the prototype chain. So your code is really equivalent:

 var foo = Date.prototype.getDate; foo(); 

(Check this yourself: check in the console that (new Date).getDate === Date.prototype.getDate really true .)

Now, it should be clear that there is no actual context for this call. You can preset it manually using the bind function for the object. (Note: older browsers need shiv for Function.prototype.bind .)

 var foo = Date.prototype.getDate.bind(new Date); foo(); 

Alternatively, set up the correct this context when you call / apply execute the function.

 var foo = Date.prototype.getDate; foo.call(new Date); 
0
source

The function is not properly linked in your example. The "this" object for this call to foo is not the original date object.

One way to do the logical work is to link the function:

 var x = new Date(); var foo = x.getDate.bind(x); foo(); 
+4
source

The problem is that this , when you call the function, is not a date, but a global context ( window ).

You can do it:

 foo.call(new Date()); 

Or, if you want to use the function from anywhere and still use the original date, you can use

 var date = new Date(); var foo = function() { return date.getDate() }; // returns always the same date 

or

 var foo = function() { return (new Date()).getDate() }; // returns the current date 

If not for IE8, you could also use bind :

 var foo = date.bind(date); 
+1
source

What you want to do is either

 var date = new Date; var foo = date.getDate.bind(Date) foo() 

or

 var date = new Date; var foo = date.getDate; foo.call(date); 

When you call foo just like you, it will not reference the date object, so it throws an error.

0
source

Because foo in your code is just a function that does not bind to any object. Calling requires other information from a Date object. You can do it:

 var date = new Date() var foo = date.getDate foo.call(date) 
0
source

Source: https://habr.com/ru/post/1493821/


All Articles