动态原型模式
作者:互联网
动态原型模式
通过开关 动态添加函数的方法
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<button onclick="fn()">点击 增/删 sayName方法</button>
<button onclick="xh()">点击实例化 小红 对象</button>
<script>
var folat = false;
var xiaohong,xiaoming;
function Preson(name, age, gender){
//凡是后期需要修改的值 都放在构造函数的this.属性名称的方式来实现继承
this.name = name;
this.age = age;
this.gender = gender;
this.like = ['小猫','小狗','小鸟'];
//刚开始folat = false 所以实例化出来的方对象没有sayName方法
if(folat){
Preson.prototype.sayName = function(){
console.log(this.name)
}
}else{
Preson.prototype.sayName = null;
}
}
function fn(){
folat = !folat;
}
function xh(){
xiaohong = new Preson('小红',16,'女');
}
</script>
</body>
</html>
运行结果如下:
标签:function,folat,name,gender,Preson,模式,sayName,原型,动态 来源: https://blog.csdn.net/qq_41614928/article/details/94589487