1 Star 0 Fork 0

老付做菜/js继承方式

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
02借助构造函数传参数.html 1.34 KB
一键复制 编辑 原始数据 按行查看 历史
老付做菜 提交于 2022-01-05 17:05 . 01上传几个文件
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script>
function Parent(name) {
this.name = name || '干饭人';
this.run = function () {
console.log(this.name + '干饭');
}
}
Parent.prototype.say = function(){
console.log('我是' + this.name);
}
// 在子类构造函数中通用 call() 调用父类型构造函数
function Child(name) {
//call改变指向。 new关键字实例化的对象 this现在是指向child1
Parent.call(this, name);
}
let son = new Child('到点了?'); //'到点了?'作为参数传给父类
son.run(); // 到点了?干饭
son.say(); // Uncaught TypeError: child1.say is not a function
/*
优点:1.避免了引用类型的属性被所有实例共享
2.可以在Child中的向Parent传参数
缺点:1.只能继承父类的实例属性和方法,不能继承原型属性和方法,调用会报错
2.无法实现函数复用,每次创建实例都会创建一遍
*/
</script>
</body>
</html>
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/laofu0514/js-inheritance-method.git
[email protected]:laofu0514/js-inheritance-method.git
laofu0514
js-inheritance-method
js继承方式
master

搜索帮助