我刚刚开始阅读Javascript,我似乎无法找到这个问题的答案。假设我有一个名为test
的函数和一个分配给变量的匿名函数说temp
。我注意到当我使用变量创建一个新的对象实例时,如示例2中那样分配了__proto__
?为什么会这样?
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?
我正在使用命令node test.js
答案 0 :(得分:4)
没有分配
__proto__
?
当然是。在这两种情况下d.__proto__
都会返回原型。区别仅在于console.log
选择呈现该值的方式。如果您使用console.dir
,则应该看到这些对象(几乎)相同。
以下是演示console.log
输出如何不同的示例:
> console.log({constructor: function foo() {}});
foo { constructor: [Function: foo] }
> console.log({constructor: function bar() {}});
bar { constructor: [Function: bar] }
> console.log({constructor: function () {}});
{ constructor: [Function] }
除了分配给constructor
的函数有不同(或没有)名称外,您是否看到对象基本相同?
console.log
只是为对象的表示添加前缀,其值为constructor.name
。
打印{}?为什么会这样?
控制台尝试推断"类型"对象以某种方式。由于第一个函数具有名称(test),因此它将使用该名称作为"类型"在输出中。
第二个功能没有名称,所以它不知道要显示什么。
更具体地说
console.log(d.constructor.name)
将为第一个函数记录"test"
,为第二个函数记录一个空字符串(""
)。
console.log
的行为未标准化, browsers JavaScript环境的输出可能不同。功能上两个例子都是相同的。