SoFunction
Updated on 2025-04-13

Laoyu A brief discussion on javascript object-oriented programming

The sigh is to ease the serious atmosphere and bring out the topic to talk about today, "javascript object-oriented programming". Next, we focus on several major object-oriented keywords: encapsulation, inheritance, polymorphism, and expansion.
Encapsulation: In the pattern of creating objects in JavaScript, I personally think that closures can be considered true encapsulation, so first let’s briefly introduce closures and see the following example:
Copy the codeThe code is as follows:

<script type="text/javascript">// <![CDATA[
function myInfo(){
var name ="Old Fish",age =27;
var myInfo = "my name is" + name + "i am" + age +"years old";
function showInfo(){
alert(myInfo);
}
return showInfo;
}
var oldFish = myInfo();
oldFish();
// ]]></script>

Doesn't it look familiar? That's right, this is actually a simple closure application. Let me briefly explain: the variable defined in the above function myInfo is accessible in its embedded function showInfo (this is easy to understand), but when we assign the return reference of this embedded function to a variable oldFish, the function showInfo is called outside the body of the myInfo function, but we can also access the variables defined in the function body. oh yeah!
Let's summarize the principle of closures: functions run in the scope that defines them rather than calling them. In fact, returning an embedded function is also the most commonly used method to create closures!
If you think the above explanation is too abstract, then let's reshape the above function to see if this is more distinct:
Copy the codeThe code is as follows:
<script type="text/javascript">// <![CDATA[
var ioldFish = function(name,age){
var name = name,age = age;
var myInfo = "my name is" + name + "i am" + age +"years old";
return{
showInfo:function(){
alert(myInfo);
}
}
}
ioldFish("Old Fish", 27).showInfo();
// ]]></script>

The encoding style in the above example is more common in ext yui, with clear distinction between public and private, and clear at a glance. Through closures, we can easily hide some things that do not want to be directly accessed by the outside. If you want to access the variables defined in the function, you can only access them through specific methods. You cannot access them directly from the outside. It is very tiring to write. After spending a while, I finally turned back. Encapsulation, isn't it just to hide things that you don't want to be seen by others! Ha ha……
If the above example is converted to JQ style, it should be written as follows. This encapsulation mode belongs to the portal open mode, and the variables defined in it can be accessed externally (in the following example, if you first instantiate an object, and then access the name or age attribute of the object outside the function, you can read it). Of course, in this mode, we can set some "unspoken rules" to let team development members understand which variables are private. Usually, we artificially underline "_" before private variables and methods to identify the warning signal! Thus, "encapsulation" is realized!
Copy the codeThe code is as follows:
<script type="text/javascript">// <![CDATA[
var ioldFish = function(name,age){
return (name,age);
};
= ={
init:function(name,age){
= name;
= age;
return this;
},
showInfo:function(){
var info = "my name is" + +"i am " ++"years old";
alert(info);
}
};
= ;
ioldFish("Old Fish",27).showInfo();
//var oldFish = new ioldFish("Old Fish",27);
//alert();
// ]]></script>

Some people may ask, which model is better? How do you say this? Both methods have advantages and disadvantages, just use them together! In short, one principle is that things that must not be directly accessed by external objects should be encapsulated with closures. The four words "must be sure" are very profound, and only by continuous practice can you understand the true meaning!
Inheritance: When mentioning this, I should add one more sentence: One of the disadvantages in closure encapsulation is not conducive to the derivation of subclasses, so closures are risky, so you need to be cautious when encapsulating them! To be intuitive, the method of creating objects in the following example adopts the "portal open" mode.
In JavaScript, inheritance is generally divided into three ways: "classical inheritance", "prototype inheritance", and "meta-blended class". The following briefly introduces the principles of the three types of inheritance methods.
A. Classical inheritance: This is a commonly used inheritance method in mainstream frameworks now. See the following example:
Copy the codeThe code is as follows:
<script type="text/javascript">// <![CDATA[
var Name = function(name){
= name;
};
= function(){
alert();
};
var Fish = function(name,age){
(this,name);
= age;
};
= new Name();
= Fish;
= function(){
alert();
}
var ioldFish = new Fish("Old Fish",27);
();
// ]]></script>

The getName method is not defined in the subclass Fish above, but the instance object ioldFish of the subclass Fish still calls this method, because the subclass Fish inherits the getName method defined in the superclass Name. To explain, the prototype of the subclass Fish here refers to an instance of the superclass. Although the getName method is not declared in the subclass Fish, according to the prototype chain principle, it will search for whether the method is in the previous object pointed to by the prototype. If the method is not found, the original prototype object will be searched. This is actually the principle of inheritance. Let me specifically explain here that = Fish;, since the default subclass prototype should point to itself, but before it pointed to the instance object of the superclass, it should be set back here. Of course, the relevant code can be organized through a function here to disguise extend. I will not explain it here, so you can follow my next blog post...
B. Prototype inheritance, which is better than class inheritance in terms of memory performance.
Copy the codeThe code is as follows:
<script type="text/javascript">// <![CDATA[
function clone(object){
var F = function(){};
= object;
return new F();
};
var Name = {
name:"who's name",
showInfo:function(){
alert();
}
};
var Fish = clone(Name);
// = "Old fish";
();
// ]]></script>

It is obvious that the core of prototype inheritance is this clone function, which is also the principle of the prototype chain. The difference is that it directly clones the superclass, so that the subclass inherits all the attributes and methods of the superclass. In particular, this type of inheritance does not require creating a constructor, it only needs to create an object word variable, define the corresponding attributes and methods, and then in the subclass, you only need to reference the attributes and methods through the dot "." symbol.
C. Meta-doped class: encapsulate some commonly used methods with relatively high versatility in a function, and then assign them to the class that wants to use these methods through the following function. You can also selectively pass the required methods for different classes.
Copy the codeThe code is as follows:
<script type="text/javascript">// <![CDATA[
function agument(receveClass,giveClass){
if(arguments[2]){
var len = ;
for(i=2;i<len;i++){
[arguments[i]] = [arguments[i]];
}
}
else{
for(method in ){
if(![method]){
[method] = [method];
}
}
}
};
var Name = function(){};
={
sayLike:function(){
alert("i like oldfish");
},
sayLove:function(){
alert("i love oldfish");
}
}
var Fish = function(){};
var ioldFish = new Fish();
agument(Fish,Name,"sayLove");
();
();
// ]]></script>

Polymorphism: I personally think this is relatively abstract and difficult to express, so I will briefly explain it from the two aspects of overloading and covering.
Overload: In the above example, the agument function initially takes two parameters, but in the subsequent call, the agument(Fish,Name,"sayLove") can also bring any multiple parameters. The overload of javascript is implemented by the user in the function by operating the arguments attribute.
Overwrite: This is very simple. If the method defined in the subclass has the same name as the method inherited from the superclass, overwrite this method (this is not overwriting the method in the superclass, pay attention). This is not a burden here!
Finally, let’s focus on this and the execution context. In the encapsulation example mentioned above, this represents the instantiation object itself of the class where this is located, but it is not the same. For example, the event processing code defined by HTML attributes is shown in the following code:
Copy the codeThe code is as follows:
<script type="text/javascript">// <![CDATA[
var Name = function(name) {
= name;
= function () {
alert();
}
};
var ioldFish = new Name("old fish"),
btn = ('btn');
= ;
// = function(){(ioldFish)};
// ]]></script>

In the above example, after clicking the button, the pop-up box does not display the attributes of the instance object. This is because the execution context of this has changed. The context he is in now should be the HTML tag input, but the attribute getName does not exist for the tag, so naturally the attribute value of this attribute cannot be output! From this example, it is not difficult to see that the execution context is determined only when it is executed, and it can change at any time.
Of course, you can remove the code I commented out above and change the execution context of this by calling to get the getName method. The apply method can also implement the function of changing the execution context, but a more beautiful implementation method bind is found in the prototype framework. Let’s take a look at the implementation of this method, and I have to sigh at the greatness of our ancestors…
Copy the codeThe code is as follows:

= function(obj) {
var method = this,
temp = function() {
return (obj, arguments);
};
}

I believe that if you can understand it, you can already write a simple script framework based on these knowledge points. Practice more, and I believe that experts will be able to advance to the level in the near future! If you don't understand it, don't worry. Object-oriented is a bit abstract. Practice more, it should be OK. Come on...
This article will end with you. The next article can be discussed with you. Please stay tuned for the design pattern of JavaScript.