JS继承封装

<script>
var extend = function (subClass, superClass) {
//1.继承类的中间类
var Tmp = function() {};
//2.将父类的原型传递给中间类
Tmp.prototype = superClass.prototype;
//3.设值继承关系
subClass.prototype = new Tmp();
subClass.prototype.constructor = subClass;
//4.将父类的this转换成当前类的this
subClass.convertASThis = superClass.prototype;
}

function Person(name) {
this.name = name;
}
function Author(name, books) {
//使用call方法将父类的this转换为本类的this,并将name属性合并到当前类
Author.convertASThis.constructor.call(this, name);
this.books = books;
this.getInfo = function() {
return this.name + " -> " + this.books;
}
}

onload = function() {

extend(Author, Person);

var a = new Author("aa", "bb");

alert(a.getInfo());
}
</script>

时间: 2024-08-26 02:03:10

JS继承封装的相关文章

js继承的常用方式

写在前面的话:这篇博客不适合对面向对象一无所知的人,如果你连_proto_.prototype...都不是很了解的话,建议还是先去了解一下JavaScript面向对象的基础知识,毕竟胖子不是一口吃成的. 我们都知道面向对象语言的三大特征:继承.封装.多态,但JavaScript不是真正的面向对象,它只是基于面向对象,所以会有自己独特的地方.这里就说说JavaScript的继承是如何实现的. 学习过Java和c++的都知道,它们的继承通过类实现,但JavaScript没有类这个概念,那它通过什么机

JS继承——原型的应用

前面我们知道JS是基于对象编程的一种脚本语言,在JS本着一切皆对象的原则,对象之间也涉及到了继承,不过这里的继承与我们以往学习过的继承有所不同,它运用的是对象的原型,来构造一个原型链来实现对超类对象的继承. 1.如何实现对象继承 function Box() { //Box 构造<span style="font-family:Arial;font-size:18px;">,超类对象</span> this.name = 'Lee'; } Desk.protot

JavaScript基础--面向对象三大特性(八):继承封装多态

一.构造函数基本用法:function 类名(参数列表){属性=参数值} 1 function Person(name,age){ 2 this.name = name; 3 this.age = age; 4 } 5 6 //创建Person对象的时候,可以直接给名字和年龄 7 var p1 = new Person('abc',80); 8 window.alert(p1.name); 9 var p2 = new Person('hello',9); 10 window.alert(p2.

JS继承的实现方式

前言 JS作为面向对象的弱类型语言,继承也是其非常强大的特性之一.那么如何在JS中实现继承呢?让我们拭目以待. JS继承的实现方式 既然要实现继承,那么首先我们得有一个父类,代码如下: // 定义一个动物类 function Animal (name) { // 属性 this.name = name || 'Animal'; // 实例方法 this.sleep = function(){ console.log(this.name + '正在睡觉!'); } } // 原型方法 Animal

Node.js模块封装及使用

Node.js中也有一些功能的封装,类似C#的类库,封装成模块这样方便使用,安装之后用require()就能引入调用. 一.Node.js模块封装 1.创建一个名为censorify的文件夹 2.在censorify下创建3个文件censortext.js.package.json.README.md文件 1).在censortext.js下输入一个过滤特定单词并用星号代替的函数. var censoredWorlds=["sad","bad","mad&

js继承的实现

js继承有5种实现方式: 1.继承第一种方式:对象冒充   function Parent(username){     this.username = username;     this.hello = function(){       alert(this.username);     }   }   function Child(username,password){     //通过以下3行实现将Parent的属性和方法追加到Child中,从而实现继承     //第一步:this.

js继承有5种实现方式

js继承有5种实现方式:1.继承第一种方式:对象冒充  function Parent(username){    this.username = username;    this.hello = function(){      alert(this.username);    }  }  function Child(username,password){    //通过以下3行实现将Parent的属性和方法追加到Child中,从而实现继承    //第一步:this.method是作为一

简单的JS运动封装实例---侧栏分享到

1 <!DOCTYPE HTML> 2 <html> 3 <head> 4 <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> 5 <title>无标题文档</title> 6 <style> 7 #div1 {width: 100px; height: 200px; background: red;

5种JS继承方法

<!DOCTYPE html> <html> <head> <meta charset=" utf-8"> <meta name="author" content="http://www.jb51.net/" /> <title>5种JS继承方法</title> <script type="text/javascript"> //1