我目前正在学习 javascript 的基础知识,但我很难理解这个图(如下)。调用 FirmAnswer.get() 时,为什么值是 42!!?不是应该是未定义的吗?因为如果我没有记错的话,function fn2() 中 return this.val 中的 this 指的是firmAnswer。
归功于图表所有者
最佳答案
because if I'm not mistaken the this in return this.val in function fn2() refers to firmAnswer
是的,确实如此,但是当您尝试从对象检索属性 (val
) 时,如果对象本身没有该属性,JavaScript 引擎将查找该对象的原型(prototype)。 firmAnswer
的原型(prototype)是 answer
(因为这是 Object.create
用于设置的),确实有一个 val
,因此使用该属性的值。这称为原型(prototype)链,是原型(prototype)继承的关键。
这是一个更简单的示例:
// Create an object with a `val`
var p = {
val: "p's value"
};
// Create an object using `p` as its prototype
var o = Object.create(p);
// Use `val` from `o` -- since `o` doesn't have `val`, the engine
// looks to `p`
snippet.log(o.val); // "p's value"
// Give `o` its own `val`
o.val = "o's value";
// Use it
snippet.log(o.val); // "o's value"
// Since this is based on whether `o` has `val` at all
// (not the *value* of `val`), we can *remove* `val`
// from `o` and start using `p`'s again:
// Remove `val` from `o` entirely
delete o.val;
// Use `val` again -- and we're back to using `p`'s
snippet.log(o.val); // "p' s value ""
<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
关于javascript - 使用 JS 多态性和方法重写,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31365149/