(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:
- A new object is created, inheriting from Foo.prototype.
- 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.
- 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/