您的位置:首页 > Web前端 > JavaScript

JS继承的实现及公有、私有、静态方法的书写

2016-02-15 17:36 645 查看
今天没事的时候,研究了一下JS继承的实现,下面是html的源码:

<!DOCTYPE html>

<html>

<head>

<meta charset="UTF-8">

<title>JS类的继承的实现</title>

<script type="text/javascript">
//定义父类及公有、私有、静态属性及方法
function parent(){
var pname = "private";//私有属性
var pfun = function(){//私有方法
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());

  }

</script>

</head>

<body onload="init();">

<header>页眉</header>

</body>

</html>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息