English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
今天没事的时候,研究了一下JS继承的实现,下面是htmlsource code:
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>JS类的继承的实现</title> <script type="text/JavaScript"> //Define the superclass and public, private, static properties and methods function parent() { var pname = "private";//private property var pfun = function() {//private method console.log("调用类的私有方法"); } this.getName = function(name) {//公有方法 this.name = name;//公有属性 return pname+"私有属性+公有属性"+this.name+"调用类的共有方法"; } } //定义静态属性及方法 parent.staticPro = "static property"; parent.staticFun = function(){ var str = "invoke class's static function"; return str; } //方法1 原型链继承 function childOne(){}; childOne.prototype = new parent(); //方法2 call/apply继承 function childTwo(){ parent.call(this); } function init(){ var c1 = new childOne(); console.log(c1.getName("child1"));// console.log(c1.name); var c2 = new childTwo(); console.log(c2.getName("child2")); console.log(c2.name); console.log(parent.staticPro); console.log(parent.staticFun()); }页眉