JS实现继承

1.作用:

改变this指向

2.使用

A.父子类的继承

<html>
<head>
</head>
<body>
	<script type="text/javascript">
		// 定义父类
		function Parent(name) {
			this.name = name;
			this.sayName = function () {
				// alert(this.name);
				console.log(this.name);
			}
		}

		// 定义子类
		function Child(name, password) {
			this.passsword = password;
			this.info = function () {
				// alert(this.password);
				console.log(this.passsword);
			}
			// 此句代码就实现了继承
			Parent.call(this, name);
		}

		// 创建对象
		var parent = new Parent("zhangsan");
		var child = new Child("lisi", "123");
		parent.sayName(); // zhangsan
		child.info();    //  123
		child.sayName(); // lisi
	</script>
</body>
</html>

B.方式一 Object.create()

原生方式继承

	<script type="text/javascript">
		// 方式1继承
		// function Person(name, age) {
		// 	this.name = name;
		// 	this.age = age;
		// }
		// function Animal() {

		// }
		// Animal.prototype.info = info;
		// function info() {
		// 	alert(this.name + " , " + this.age);
		// }

		// Person.prototype = Object.create(Animal.prototype);
		// Person.prototype.constructor = Person;
		// var p1 = new Person('lisi', 60);
		// p1.info();
   </script>

C.方式二

	<script type="text/javascript">
		// function Person(name, age) {
		// 	this.name = name;
		// 	this.age = age;
		// }

		// function info() {
		// 	alert(this.name + " , " + this.age);
		// }

		// var p1 = new Person('lisi', 60);
		// p1.show=info; //对对象添加属性,不优雅
		// p1.show();
	</script>

D.方式三 call()

	<script type="text/javascript">
		function Person(name, age) {
			this.name = name;
			this.age = age;
		}
		function info() {
			console.log(this.name + " , " + this.age);
		}
		var p1 = new Person('lisi', 60);
		info.call(p1);
		p1.info();
	</script>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值