Introduction to the encapsulation of JavaScript inheritance

  • 2020-03-26 21:24:25
  • OfStack

 
 
function extend(obj,prop){ 
function F(){ 

} 
//If the first argument is of type object (that is, a json object), the json key value is assigned to the F function's prototype, f.prototype.key = value
if (typeof(obj) == "object") { 
for(var name in obj){ 
F.prototype[name] = obj[name]; 
} 
} else {//If the first parameter is of type function, assign the prototype of the secondary function to the F function. Prop must be passed (json object), so assign prop to the prototype of the F function
F.prototype = obj.prototype; 
for(var name in prop){ 
F.prototype[name] = prop[name]; 
} 
} 
return F; 
} 
//Since there is only one parameter, the key and value of the json object will be assigned to the F function prototype in the extend function, and then the F function will be received with the person variable. At this point, the person will also become a function, and this function will also have the prototype name and sex of the F function
var person = extend({ 
name:"xxc", 
sex:"man" 
}); 
//After passing in the person function and entering the extend function, first assign the prototype of person to the F function, and then assign the second parameter hope:"more money" to the F function. At this time, the prototype of the F function has three things: name,sex,hope
//Finally, the F function is returned, causing the prototype of the person to be the same as the F function, with name,sex,hope
var person = extend(person,{ 
hope:"more money" 
}); 
alert(person.prototype.name);//xxc 
alert(person.prototype.sex);//man 
alert(person.prototype.hope);//more money 

 
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> 
<html> 
<head> 
<title>function.html</title> 

<meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> 
<meta http-equiv="description" content="this is my page"> 
<meta http-equiv="content-type" content="text/html; charset=UTF-8"> 
<script src="../jquery/jquery-1.10.2.min.js"></script> 
<script src="extends2.js"></script> 
<!--<link rel="stylesheet" type="text/css" href="./styles.css">--> 

</head> 

<body> 
</body> 
</html> 

Related articles: