javascript - 使用 JS 多态性和方法重写

标签 javascript object inheritance

我目前正在学习 javascript 的基础知识,但我很难理解这个图(如下)。调用 FirmAnswer.get() 时,为什么值是 42!!?不是应该是未定义的吗?因为如果我没有记错的话,function fn2()return this.val 中的 this 指的是firmAnswer。

归功于图表所有者

enter image description here

最佳答案

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/

相关文章:

两个对象的Javascript联合

javascript - JS - 按值获取对象中的数组

javascript - 在类函数中访问 JavaScript 类变量

javascript - 将可点击的坐标图像更改为 css

javascript - sequelizejs 关系/关联、hasMany/belongsTo 与定义模型上的引用

java - 返回二维数组 java.lang.Object 中任意对象的索引。

python - 跳过父方法的 pythonic 方法是什么?

c++ - 为什么 C++ 编译器不能区分继承的公共(public)方法和继承的同名私有(private)方法?

JavaScript 原型(prototype)父类(super class)

javascript - 使用 ng-repeat 定位 3d 对象