Bind binding failure in JavaScript

the first paragraph of code:

function add(){
    console.log(this.x + this.y);
};

var obj = {
    x: 2,
    y: 3
};

setTimeout(add.bind(obj), 1000);

the callback function above can be called correctly, and the result 5

is displayed.

second paragraph code:

 console.log  return
function add(){
    return (this.x + this.y);
};

var obj = {
    x: 2,
    y: 3
};

setTimeout(add.bind(obj), 1000);

the callback function above, there is no result of the call, and there is no error?

Mar.31,2021

the function of console.log is to output information, and you have no place to display the return value of the output add function


you didn't print it, you can do this:

setTimeout(function() {
  console.log(add.bind(obj)());
}, 1000);

you write

in the js file.
var a = 1;
console.log(a); //  1
var a = 1;
a; // 

the second type is
clipboard.png


console

  • one is to record what is required by errors, reminders and console.log, etc.
  • the second is to return the last value running in the console that returns the console environment.

you can also see the obvious difference:

// Test 1
> var a = 1; console.log(a)
  1
< undefined
// Test 2
> var a = 1; a
< 1

> is the input that requires the console to execute;
< is the output, and what the request for execution returns to the console; and the blank 1 in
Test 1 is something that the console is required to record.

look at the question after understanding. < 2094 setTimeout is the basic meaningless number returned by the browser for tagging. (it seems that it can only be used for clearTimeout ) specific self-check. And because you are running on the console, it is returned to the console, so the console appears 2094. Then the front of the 5 is in vain, indicating that it is required to be recorded by a certain piece of code.

The return of the second paragraph is returned, because this code is executed by setTimeout , so it is returned to setTimeout (or window ? Anyway, it is not the console, not the console, and it is impossible for the console to return a value to it (the reason is not explained), so the console returns the last value returned to it, that is, another random meaningless number marked setTimeout < / console >. And there is no console.log required to record, so there are no new results.

instead of what bind fails.

think about the answers of other respondents. This question may be too simple, maybe not many people want to talk to you.

MySQL Query : SELECT * FROM `codeshelper`.`v9_news` WHERE status=99 AND catid='6' ORDER BY rand() LIMIT 5
MySQL Error : Disk full (/tmp/#sql-temptable-64f5-1b3b787-2c2a2.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
MySQL Errno : 1021
Message : Disk full (/tmp/#sql-temptable-64f5-1b3b787-2c2a2.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
Need Help?