简体   繁体   English

JavaScript Prototype 属性窃取/继承

[英]JavaScript Prototype property stealing / inheritance

Is this the correct way to do prototype inheritance and property 'stealing??'/inheritance.这是进行原型继承和属性“窃取??”/继承的正确方法。 I want to inherit all properties from the Person constructor + all methods.我想从 Person 构造函数+所有方法继承所有属性。

function Product(name, price) {
    this.name = name;
    this.price = price;
}
Product.prototype.tellMe = function() {
    console.log('Name = ' + this.name + ', Price = ' + this.price);
}

function Food(name, price, category) {
    Product.call(this, name, price);
    this.category = category;
}
Food.prototype = Object.create(Product.prototype);
Food.prototype.constructor = Food;

var b = new Food('Name', 123, 'Category');
console.log(b);
b.tellMe();
var a = new Product('Name2', 321);
console.log(a);

I would appreciate if you could give me a good example.如果你能给我一个很好的例子,我将不胜感激。 Thanks!谢谢!

Yes, that is the right way to use the constructor/prototype (aka pseudo-classical) pattern.是的,这是使用构造函数/原型(又名伪经典)模式的正确方法。

By reassigning Food.prototype to reference an object that inherits from Product.prototype you achieve access to all the methods that are defined in it for all the instances of Food .通过重新分配Food.prototype以引用继承自Product.prototype的对象,您可以访问其中为所有Food实例定义的所有方法。 And by calling the Product.call(this, name, price) you add the properties name and price in the newly created objects.并通过调用Product.call(this, name, price)在新创建的对象中添加属性nameprice

The difference is that the properties are going to be "own" properties of the Food objects (they're going to actually be inside the b object, for example), whereas the methods are available to them through prototypal delegation.不同之处在于属性将是Food对象的“自己的”属性(例如,它们实际上将位于b对象内部),而方法可通过原型委托对它们可用。 That is, the instances of Food are going to delegate the method calls to their prototype, Food.prototype , which in turn will delegate the calls to its prototype, Product.prototype .也就是说, Food的实例会将方法调用委托给它们的原型Food.prototype ,而后者又会将调用委托给它的原型Product.prototype

Put in plain words, JS will search for tellMe in b and since it can't find it in there, it searches for it in its prototype Food.prototype .简而言之,JS 会在b中搜索tellMe ,由于在其中找不到它,它会在其原型Food.prototype中搜索它。 It's not in there either, so it moves up to its prototype Product.prototype where it finally finds that method and executes it.它也不在那里,所以它向上移动到它的原型Product.prototype ,在那里它最终找到了那个方法并执行它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM