JS中的继承实现方式

时间:2021-12-20 07:44:57

第一种:通过prototype来实现

prototype.html

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
<script type="text/javascript">
function Person(){} Person.prototype.username = "lisi";
Person.prototype.gender = "man";
Person.prototype.fav = ["read","eat"]; var p1 = new Person();
var p2 = new Person();
p2.username = "zhangsan";
//p2.fav.push("run");
var fav = p2.fav;
console.log(fav)
p2.fav = new Array();
p2.fav = p2.fav.concat(fav); p2.fav.push("run"); /*console.log(p1.username);
console.log(p1.fav);
console.log(p2.username);
console.log(p2.fav);*/ function User(){}
User.prototype = new Person();
User.prototype.password = "123123";
User.prototype.email = "admin@admin.com"; User.prototype.say = function(){
console.log(this);
}; var u = new User();
u.gretting="Hello";
var u1 = new User(); console.log(u.username)
u.say();
u1.say(); </script>
</head>
<body> </body>
</html> 第二种方法:通过this关键字来实现;js中的this始终指向调用它的对象
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
<script type="text/javascript">
function Person(name,gender){
this.name = name;
this.gender = gender;
} function User(name,gender,email,password){
this.super = Person;
this.super(name,gender);
delete this.super;
this.email = email;
this.password = password;
//this.Person(name,gender);
} var p1 = new Person("lisi","man"); var u = new User("zhangsan","msn","zhnagsan@zhangsan.com","123123123");
console.log(p1.name);
console.log(u.name);
//var p2 = new Person();
//p2.name = "lisi";
//p2.gender = "man";
</script>
</head>
<body> </body>
</html> 第三种方法:通过call或者apply来实现
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
<script type="text/javascript">
function Person(name,gender){
this.name = name;
this.gender = gender;
} function User(name,gender,email){ //对象冒充 动态改变 函数的执行上下文
//Person.call(this,name,gender);
Person.apply(this,[name,gender]); this.email = email; this.say = function(msg){
console.log(this);
console.log(msg);
}
} var u = new User("lisi","man","lisi@lisi.com");
console.log(u.gender);
u.say("Hello"); u.say.call(new Person("",""),"Hello1");
u.say.apply(window,["lisi"]); console.log("--------------------")
var name = "lisi";
var obj = {
name:"zhangsan",
say:function(){
console.log(this.name);
return function(){
console.log(this.name);
return function(){
console.log(this.name);
return {
name:"wangwu",
say:function(){
console.log(this.name);
} }
}
}
}
}; obj.say().call(obj)().say.apply(this); //obj.say()();
</script>
</head>
<body> </body>
</html>