2015-12-19 78 views
-3

下面的代码是打印“helloundefined”,但我希望它打印出“你好”。无法理解Javascript输出

var proto = { 
    age: function(a) { 
     console.log(a+this.val) 
    } 
}; 
; 
var a = { val: "there" }; 
a = Object.create(proto); 

a.age("hello"); 
+0

使用调试器来逐步执行代码,并看它在做什么。 –

回答

0
var a = { val: "there" }; 

你分配一个对象a

a = Object.create(proto); 

...你立即与具有对象不连接的新对象覆盖你在前一行创建。

说上一个对象没有指向它的引用并获取垃圾回收。

您似乎在寻找Object.setPrototypeOf(a, proto);(警告:ES6)。

var proto = { 
 
    age: function(a) { 
 
     console.log(a+this.val) 
 
    } 
 
}; 
 
; 
 
var a = { val: "there" }; 
 
Object.setPrototypeOf(a, proto); 
 
a.age("hello");

+0

好吧...明白了,添加属性'val'的正确方法是在object.create下写a.val =“there”.. –

+0

@MukulChakravarty:是的,确切地说,你应该这样做。 'Object.setPrototypeOf'有点鄙视 – Bergi

+0

@Quentin谢谢.. –