Home  >  Article  >  Web Front-end  >  Javascript simply implements object-oriented programming and inherits example code_javascript skills

Javascript simply implements object-oriented programming and inherits example code_javascript skills

WBOY
WBOYOriginal
2016-05-16 15:29:24927browse

This article describes the simple implementation of object-oriented programming inheritance example code in Javascript. Share it with everyone for your reference, the details are as follows:

Object-oriented languages ​​must have four basic characteristics:

1. Encapsulation ability (that is, allowing variables or functions of basic data types to be put into a class to form members or methods of the class)
2. Aggregation capability (that is, allowing classes to contain classes, so that complex enough designs can be handled)
3. Support inheritance (the parent class can derive subclasses, and the subclasses have the attributes or methods of the parents)
4. Support polymorphism (allowing the same method name to have independent processing methods depending on the method signature [i.e., the parameters of the function])

Javascript can support these four basic attributes, so JavaScript is indeed a weakly typed object-oriented language. Here is a simple class inheritance code

<script type="text/javascript">
//父类ClassA
function ClassA(sColor) {
  this.color = sColor;
  this.sayColor = function () {
    document.write("Color:" + this.color + "<br/>");
  };
}
//子类ClassB,继承自ClassA
function ClassB(sColor,sName){  
  ClassA.call(this,sColor);//利用call函数,将ClassA的所有方法都赋给ClassB,即实现了继承
  this.name = sName;
  this.sayName = function(){
    document.write("Name:" + this.name + "<br/>");
  }
}
var oClassA = new ClassA("Red");
oClassA.sayColor();
var oClassB = new ClassB("Blue","Jimmy.Yang");
oClassB.sayColor();//这里sayColor方法是从ClassA继承来的
oClassB.sayName();//这是ClassB中的新方法
/*
call函数的演示示例
function sayColor(sPrefix, sSuffix) {
alert(sPrefix + this.color + sSuffix);
};
var obj = new Object();
sayColor.call(obj, "The color is ", ", a very nice color indeed. ");
*/
</script>

I hope this article will be helpful to everyone in JavaScript programming.

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn