gpt4 book ai didi

javascript - 两个 JavaScript 类之间的区别以及为什么原型(prototype)不适用于 Emp 类

转载 作者:行者123 更新时间:2023-11-29 10:07:52 25 4
gpt4 key购买 nike

(function() {

var Emp = function(_name, _salary) {
var name = _name;
var salary = _salary
return {
name: name,
salary: salary
};
}

Emp.prototype.work = function(){
console.log('this is work',this);
}

var Car = function(_name, _model) {
this.name = _name;
this.model = _model;
}

Car.prototype.drive = function() {
console.log('this is drive ', this);
}

var car = new Car('bmw', '2015');
car.drive(); // Works

var emp = new Emp('peter', '1234');
emp.work(); // TypeError
})();

我能够理解 Car 类,但是为什么原型(prototype)在 Emp 类上不起作用,请帮助我理解这个基本的 JavaScript 概念。

最佳答案

MDN page关于 new 运算符,解释了该运算符的本质作用:

When the code new Foo(...) is executed, the following things happen:

  1. A new object is created, inheriting from Foo.prototype.
  2. The constructor function Foo is called with the specified arguments, and with this bound to the newly created object. new Foo is equivalent to new Foo(), i.e. if no argument list is specified, Foo is called without arguments.
  3. The object returned by the constructor function becomes the result of the whole new expression. If the constructor function doesn't explicitly return an object, the object created in step 1 is used instead. (Normally constructors don't return a value, but they can choose to do so if they want to override the normal object creation process.)

Emp 构造函数的最后一步是

return {
name: name,
salary: salary
};

您“覆盖”了返回在步骤 1 中创建的对象的默认行为,因此您没有从函数原型(prototype)继承

关于javascript - 两个 JavaScript 类之间的区别以及为什么原型(prototype)不适用于 Emp 类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39678942/

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