js给原型增加新属性和方法

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Dog</title>
    <script>
        //给原型增加新属性和方法
        function Dog(name, breed, weight){
            this.name = name;
            this.breed = breed;
            this.weight = weight;
        }

        Dog.prototype.species = "Canine";
        Dog.prototype.bark = function(){
            if (this.weight > 25){
                console.log(this.name + " Woof");
            }
        };

        var fido = new Dog("fido", "mixed", 38);
        fido.bark();

        //给原型添加方法后所有的继承者都拥有该方法,属性也是如此
        var barnaby = new Dog("Barnaby", "Basset Hound", 55);
        Dog.prototype.sit = function(){
            console.log(this.name + " is now sitting");
        };

        barnaby.sit();


    </script>
</head>
<body>

</body>
</html>
原文地址:https://www.cnblogs.com/themost/p/9363987.html