添加绑定函数
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>扩展原型对象</title>
</head>
<body>
</body>
</html>
<script>
function Animal(name,color,Do) {
this.name = name;
this.color = color;
this.Do = function () {
console.log("swimming")
}
}
var fish = new Animal("fish","gold");
console.log(fish);
Animal.prototype.smile = function () {
console.log("-。-")
};
//通过prototype方式给Animal添加smile方法,其实例对象fish也能调用到新的方法
console.log(fish.smile)
</script>
构造函数constructor绑定多个方法
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>constructor</title>
</head>
<body>
</body>
</html>
<script>
function Animal(name,color) {
this.name = name;
this.color = color;
this.Do = function () {
console.log("swimming")
}
}
Animal.prototype = {
saying : function () {
console.log("hello")
},
crying : function(){console.log("呜呜呜")}
};
var A = new Animal("fish","gold");
console.log(A);
//{name: "fish", color: "gold", Do:ƒ() 以及一个对象,包含saying和crying}
console.log(A.Do);
//ƒ () {console.log("swimming")}
console.log(A.saying);
//ƒ () {console.log("hello")}
console.log(A.crying);
//ƒ () {console.log("呜呜呜")}
</script>