gpt4 book ai didi

javascript - __proto__ 和 JavaScript 中的继承

转载 作者:数据小太阳 更新时间:2023-10-29 05:27:33 28 4
gpt4 key购买 nike

我已经研究了几天 JavaScript 继承,虽然我已经取得了很大的进步,但有些事情我还不太明白。

例如,我发现这种行为非常令人困惑:

var Employee = function Employee() { this.company = 'xyz'; };
var Manager = function Manager() { this.wage = 'high'; };

var m = new Manager();

m; // { "wage": "high", __proto__ : Manager } -- no problems so far.

Manager.prototype = new Employee();

var n = new Manager;

m.company; // undefined
n.company; // "xyz"

m__proto__ 属性指向一个不是 Managercurrent 原型(prototype)的对象。这有点违反直觉,因为:

An object inherits properties even if they are added to its prototype after the object is created.

Taken from JavaScript: The Definitive Guide, 5th Edition, By David Flanagan

难道这种行为不也适用于上述案例吗?

谁能澄清一下?

最佳答案

这有点令人困惑,因为函数本身就是对象:

function Employee() {this.company = 'xyz';}
function Manager() {}

var m = new Manager();
Manager.prototype = new Employee();

/* You set the prototype on the Manager function (object),
your m instance and Manager function are separate objects.
At this point the prototype of m is still undefined */

m = new Manager();
m.company; // 'xyz'

/* Creating a new Manager copies the new prototype */

关于javascript - __proto__ 和 JavaScript 中的继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3475696/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com