我对 javascript 原型有点好奇,我在这里找到了示例 ,我做了一些修改,所以我可以这样尝试:
<html>
<body>
<script>
function Product(name, price) {
this.name = name;
this.price = price;
}
function Food(name, price) {
Product.call(this, name, price);
this.category = 'food';
this.otherName = name;
}
Food.prototype = new Product();
function Toy(name, price) {
Product.call(this, name, price);
this.category = 'toy';
}
Toy.prototype = new Product();
var cheese = new Food('feta', 5);
var fun = new Toy('robot', 40);
var prod = new Product('test', 20);
console.log(cheese);
console.log(fun);
console.log(prod);
</script>
</body>
</html>
它像这样返回
cheese = Food {name: "feta", price: 5, category: "food", otherName: "feta", name: undefined, price: undefined}
fun = Toy {name: "robot", price: 40, category: "toy", name: undefined, price: undefined}
prod = Product {name: "test", price: 20}
它的 make 属性name
和price
两次,如果我们区分Food.prototype = new Product();
和Toy.prototype = new Product();
为什么我必须使用那条线?