1

我对 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 属性nameprice两次,如果我们区分Food.prototype = new Product();Toy.prototype = new Product();

为什么我必须使用那条线?

4

3 回答 3

3

每个 JavaScript 对象都有第二个 JavaScript 对象(或 null,但这种情况很少见)与之关联。第二个对象称为原型,第一个对象从原型继承属性。

由对象字面量创建的所有对象都具有相同的原型对象,我们可以在 JavaScript 代码中将此原型对象称为Object.prototype. 使用 new 关键字和构造函数调用创建的对象使用构造函数的原型属性值作为其原型。因此,由创建的对象new Object() 继承自Object.prototype就像由创建的对象{}一样。类似地,由new Array()使用创建的对象Array.prototype作为其原型,由new Date()使用创建的对象Date.prototype作为其原型。

于 2013-09-16T08:36:17.053 回答
1

好吧,原型属性允许您向对象添加属性和方法。

要理解的示例:-

<!DOCTYPE html>
<html>
<body>

<script>

function employee(name,jobtitle,born)
{
this.name=name;
this.jobtitle=jobtitle;
this.born=born;
}
var fred=new employee("Fred Flintstone","Caveman",1970);

employee.prototype.salary=null;

fred.salary=20000;

document.write(fred.salary);

</script>

</body>
</html>

在上面的示例中,我们使用原型向员工添加了另外一项财产(工资) 。

希望对你有帮助...

于 2013-09-16T08:37:15.373 回答
0

像 OOP 一样,JS 中的所有对象都是 Object 类的后代,它们继承 Object.prototype 的所有属性,而您可以覆盖它们。对象也可以有空原型,即 Object.create(null)..

于 2013-09-16T08:38:56.557 回答