javascript 对象的原型

往往定义一个函数时,函数内部有关键字this时,就把这个函数当成对象,this相当于python中的self.都是对象中用到的,代表对象本身。

js不像python,在函数内部定义的子函数,在每次创建对象实例时,实例都会重复创建子函数,这样大量浪费了内存,所以要用到原型,即把子函数放到一个公共区域,这样每个实例都不会创建子函数,而是去公共区调用。

子函数,浪费内存:
 function fun(n){
	this.name=n;
	this.sayname=function(){
		console.log(this.name);
    }
}

obj1= new fun('we');
obj1.sayname();
obj1= new fun('wewe');
obj1.sayname();   


改进型:

function fun(n){
	this.name=n;
}
fun.prototype={
	'sayname':function(){
		console.log(this.name);
    }
}

obj1= new fun('we');
obj1.sayname();
obj1= new fun('wewe');
obj1.sayname();

  

猜你喜欢

转载自www.cnblogs.com/alex-hrg/p/9448250.html