gpt4 book ai didi

JavaScript,设置0x​​104567910时使用和不使用 "new"的区别

转载 作者:行者123 更新时间:2023-11-29 19:45:33 24 4
gpt4 key购买 nike

如果我在 Firefox 中运行这段 JavaScript 代码:

function Human() {

}

function Engineer(diploma) {
this.diploma = diploma;
}

Engineer.prototype = new Human();// Line A1
Engineer.prototype.constructor = Engineer;
Engineer.prototype.getDiploma = function() {
alert(this.diploma);
};
var engineer = new Engineer("Bridges and Roads");
engineer.getDiploma();
var human = new Human();
human.getDiploma(); // Line A2

标记为“A2”的行将在 Firefox 控制台中生成错误:

TypeError: human.getDiploma is not a function

另请注意,在 A1 行中,我使用“new”来模拟 Engineer 从 Human 继承。这可以在以下 JSFiddle 中进行测试:

http://jsfiddle.net/RMWdh/1/

现在我像这样更改 A1 行:

function Human() {

}

function Engineer(diploma) {
this.diploma = diploma;
}

Engineer.prototype = Human.prototype;// Line B1
Engineer.prototype.constructor = Engineer;
Engineer.prototype.getDiploma = function() {
alert(this.diploma);
};
var engineer = new Engineer("Bridges and Roads");
engineer.getDiploma();
var human = new Human();
human.getDiploma(); // Line B2

请注意,A1 行已被 B1 行替换。其余代码相同。这一次,如果我运行它,Firefox 控制台中没有错误,但我会收到一个警告说“Bridges and Roads”(这是对 engineer.getDiploma() 的调用),另一个警告说“undefined”(它是 B2 行的结果)。这也可以在 JSFiddle 上检查,在这里:

http://jsfiddle.net/RMWdh/2/

我的问题是:为什么会有这种差异?这样做有什么区别:

 Engineer.prototype = new Human();

还有这个:

 Engineer.prototype = Human.prototype;

最佳答案

后者只是复制引用,使“工程师是人类”和“人类是工程师”都为真。这通常不是预期的效果。

Engineer.prototype = Human.prototype;
var human = new Human();
/*
engineer ->
(Engineer.prototype & Human.prototype) ->
Object.prototype
*/

var human = new Human();
console.log('getDiploma' in human); // true
console.log(human instanceof Engineer); // true

另一方面,前者仅证明“工程师也是人”。这允许 Engineer 将自己的身份和逻辑与其他 Human 分开。在这种情况下,包括 .getDiploma()

Engineer.prototype = new Human();
var engineer = new Engineer("Bridges and Roads");
/*
engineer ->
Engineer.prototype ->
Human.prototype ->
Object.prototype
*/

var human = new Human();
console.log('getDiploma' in human); // false
console.log(human instanceof Engineer); // false

您还可以使用 Object.create()建立prototype chain无需调用构造函数:

Engineer.prototype = Object.create(Human.prototype);

关于JavaScript,设置0x​​104567910时使用和不使用 "new"的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20030846/

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