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>
<!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>
相关文章推荐
- JQuery1——基础($对象,选择器,对象转换)
- Android学习笔记(二九):嵌入浏览器
- Android java 与 javascript互访(相互调用)的方法例子
- JavaScript演示排序算法
- javascript实现10进制转为N进制数
- 在Windows 8.1的IE 11中屏蔽双击放大功能
- 2019年开发人员应该学习的8个JavaScript框架
- HTML中的script标签研究
- 对一个分号引发的错误研究
- 异步流程控制:7 行代码学会 co 模块
- ES6 走马观花(ECMAScript2015 新特性)
- JavaScript拆分字符串时产生空字符的原因
- Canvas 在高清屏下绘制图片变模糊的解决方法
- Redux系列02:一个炒鸡简单的react+redux例子
- JavaScript 各种遍历方式详解
- call/apply/bind 的理解与实例分享