JavaScript中继承和创建对象的几种方法

JS中的继承

通过某种方式让一个对象去继承另一个对象的属性和方法。
1,原型链继承 (有两种实现方式)

(1)Chid.prototype = Parent.prototype

弊端:Chid.prototype.constructor 指向Parent,需要手动更改为Chid 。

(2)Child.prototype = new Parent()
让子类的原型对象指向父类对象
弊端:Chid.prototype.constructor 指向Parent,需要手动更改为Chid。

<script>
	child.prototype = new Parent ;//这之后可以访问到父类的公有和私有属性
</script>

2、call继承(只能继承父类的私有属性)

<script>
	Parent.call(this);//其中this指向空对象  此代码会让Parent的this也指向这个空对象,从而可以访问到Parent的私有属性
</script>

3、组合式继承(子类可以继承父类的私有和公有属性)

<script>
	Parent.call(this);//继承私有属性
	Child.prototype = Object.creat(Parent.prototype);//让子类的原型对象指向父类的原型对象 只不过用的是通过Object.creat又克隆的一份,这样可以避免增添属性造成的错误
	Child.prototype.constructor = Child;//可以手动指向一下,避免代码出错
</script>

4、ES6中的继承
super:类似于call继承,只能继承私有属性
extends:类似于公有继承

<script>
	class Parent{
     
     
	constructor(){
     
     
	this.a=1;
			}
	}
	class Child extends Parent{
     
     
	constructor(){
     
     
	super();
	this.b=2;
			}
	}
</script>

JS中创建对象的方法

1、字面量创建对象(缺点:初始化的值都是一样的,优点:可以实现共享)

<script>
	let obj = {
     
     
	name:"wc";
	age"12;
	weight:this.age+10;//这个this表示window 
	}
	console.log(obj.weight)//NaN
</script>

注意:在一个对象的方法中,如果有this,通过这个对象调用时方法中的this指的是对象
2、使用工厂模式创建对象(可以产生很多对象,可以批量创建对象)

<script>
	function creatRect(w,h){
     
     
	var obj = {
     
     };
	obj.width = w ;
	obj.height = h ;
	obj.getS = function(){
     
     
	return this.width * this.height ;
		}
	return obj;
	}
	var rect1 =creatRsct(1,2);
	console.log(rect1.getS());
	varr rect2 = creatRect(3,4);
	console.log(rect2.getS());
</script>

3、通过构造器创建
创建对象通过new一个构造器

<script>
	var rect1 = new Rect(1,2);
</script>

4、通过构造器+原型对象来创建
添加原型对象上的一些属性

<script>
	function Rect(w,h){
     
     
	this.w = w ;
	this.h = h ;
	}
	Rect.prototype.getS = function(){
     
     
	return this.w;
	}
	var rect1 = new Rect(1,2);
</script>

5、ES6中通过class来创建类

<script>
	class Rect{
     
     
	constructor(w,h){
     
     
		this.w = w ;//私有属性
		this.h = h ;
		}
		yy = 123 ;//私有属性 
		getS(){
     
     //公有属性
		return this.w +this.h;
		}
		static xx = 10;//静态变量 类上的属性 需要通过类名来访问
	}
	var rect1 = new Rect(4,2);
	console.log(Rect.xx);//10
</script>

猜你喜欢

转载自blog.csdn.net/Fairyasd/article/details/107583200