简体   繁体   中英

using new with a variable that is assigned a function does not have an assigned __proto__

I just started reading about Javascript and I cant seem to find the asnwer to this question.Suppose I have a function called test and an anonymous function assigned to a variable say temp . I noticed that when I create a new object instance with new using a variable as in example 2 no __proto__ is assigned ? Why is that

 function test() { this.name = "testerName"; } var temp = function() { this.name = "testeragain"; } // Example 1: var d = new test(); console.log(d.__proto__) //prints test{} console.log(d.__proto__ == test.prototype) //Returns false ? shouldnt this // Example 2: var d = new temp(); console.log(d.__proto__) //prints {} ?Why is this? 

I am running my file using command node test.js

no __proto__ is assigned ?

Of course it is. In both cases d.__proto__ returns the prototype. The difference is only how console.log chooses to render that value . If you use console.dir instead you should see that those objects are (almost) the same.

Here is an example that demonstrates how the console.log output can differ:

> console.log({constructor: function foo() {}});
foo { constructor: [Function: foo] }

> console.log({constructor: function bar() {}});
bar { constructor: [Function: bar] }

> console.log({constructor: function () {}});
{ constructor: [Function] }

Do you see that the objects are basically the same, except that the functions assigned to constructor have different (or no) names?

console.log simply prefixes the representation of the object with the value of constructor.name .

prints {} ?Why is this?

The console tries to infer the "type" of the object somehow . Since the first function has a name (test) it will use that name as the "type" in the output.

The second function doesn't have a name so it doesn't know what to show.

More concretely

console.log(d.constructor.name)

will log "test" for the first function and an empty string ( "" ) for the second function.

The behavior of console.log is not standardized and the output can differ between browsers JavaScript environments. Functionally wise both examples are identical.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM