【js面向对象】常用的面向对象写法和继承写法

  前言:js在面向对象的写法有很多种,继承方式也有很多种。本篇的写法“我个人”认为比较好用,也比较简单的写法。

一、创建构造函数,并创建一个实例

function Person(name,age){       
	this.name = name;
	this.age = age;	
};
Person.prototype.sayName = function(){   
	console.log('name: '+this.name);
}; 

var nick = new Person('nick',18);
nick.sayName();

执行Person的实例nick.sayName方法,成功输出name: nick

二、对象继承写法

①、错误的继承示范

function Person(name,age){
	this.name = name;
	this.age = age;	
};
Person.prototype.sayName = function(){
	console.log('name: '+this.name);}; 

function Person2(name, age, sex){       //创建Person2 
	Person.call(this,name,age);     //继承属性
	this.sex = sex;	
}

Person2.prototype = Person.prototype;    //继承方法

Person2.prototype.sayName = function(){     //修改sayName方法
	console.log('my name is '+ this.name);	
}
Person2.prototype.saySex = function(){      //添加saySex方法
	console.log( this.sex );	
}

console.log(Person.prototype);        //输出Person.prototype对象

var nick = new Person('nick',18);
nick.sayName();
var freddy = new Person2('freddy',20,'男');
freddy.sayName();
freddy.saySex();

运行代码会发现:Person.prototype对象已经被修改,我们创建的Person的实例nick的shaName(); 输出my name is nick。这是很危险的操作,这样会影响程序的运行。


②、正确的继承示范

function Person(name,age){
	this.name = name;
	this.age = age;	
};
Person.prototype.sayName = function(){
	console.log(this.name);
}; 

function Person2(name, age, sex){
	Person.call(this,name,age);
	this.sex = sex;	
}

for(var i in Person.prototype){    //正确的继承方法
		Person2.prototype = Person.prototype[i];
	}

Person2.prototype.sayName = function(){
	console.log('my name is '+ this.name);	
}
Person2.prototype.saySex = function(){
	console.log( this.sex );	
}

console.log(Person.prototype);

var nick = new Person('nick',18);
nick.sayName();
var freddy = new Person2('freddy',20,'男');
freddy.sayName();
freddy.saySex();

运行代码:我们添加或修改继承的方法,就不会再影响Person,prototype的方法了。

相关链接: 【ES6】“面向对象写法”和继承方式

猜你喜欢

转载自blog.csdn.net/w390058785/article/details/79798419