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

标签 javascript javascript-objects

(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/

相关文章:

javascript - 使用 PhantomJS 进行响应式设计测试

javascript - JavaScript 事件处理程序中处理 'this' 的模式

php - jQuery 自定义模板无法正常工作

javascript - Protractor:访问返回对象的属性

javascript - 展平对象数组

Javascript 排序多维对象

javascript - 错误 415 : x-www-form-urlencoded versus JSON

javascript - D3 v4 Multi line chart Brush 移动画笔时发出 NaN

javascript - 创建一个新的对象数组,不重复键值对

Javascript:实例化对象数组的最佳方式