因为javascript是基于原型(prototype)的,没有类的概念(es6有了,这个暂且不谈),我们能接触到的都是对象,真正做到了一切皆为对象
所以我们再说对象就有些模糊了,很多同学会搞混类型的对象和对象本身这个概念,我们在接下来的术语中不提对象,我们使用和Java类似的方式,方便理解
方式一
类(函数模拟)
function Person(name,id){
//实例变量可以被继承
this.name = name;
//私有变量无法被继承
var id = id;
//私有函数无法被继承
function speak(){
alert("person1");
}
}
//静态变量,无法被继承
Person.age = 18;
//公有函数可以被继承
Person.prototype.say = function(){
alert("person2");
}
继承,并调用父类方法
立即学习“Java免费学习笔记(深入)”;
function Person(name,id){
//实例变量可以被继承
this.name = name;
//私有变量无法被继承
var id = id;
//私有函数无法被继承
function speak(){
alert("person1");
}
}
//静态变量,无法被继承
Person.age = 18;
//公有静态成员可被继承
Person.prototype.sex = "男";
//公有静态函数可以被继承
Person.prototype.say = function(){
alert("person2");
}
//创建子类
function Student(){
}
//继承person
Student.prototype = new Person("iwen",1);
//修改因继承导致的constructor变化
Student.prototype.constructor = Student;
var s = new Student();
alert(s.name);//iwen
alert(s instanceof Person);//true
s.say();//person2
继承,复写父类方法且实现super()
乐尚商城系统是一项基于PHP+MYSQL为核心开发的一套免费 + 开源专业商城系统。软件具执行效率高、模板自由切换、后台管理功能方便等诸多优秀特点。 本软件是基于Web应用的B/S架构的商城网站建设解决方案的建站系统。它可以让用户高效、快速、低成本的构建个性化、专业化、强大功能的团购网站。从技术层面来看,本程序采用目前软件开发IT业界较为流行的PHP和MYSQL数据库开发技术,基于面向对象的编程
684
function Person(name,id){
//实例变量可以被继承
this.name = name;
//私有变量无法被继承
var id = id;
//私有函数无法被继承
function speak(){
alert("person1");
}
}
//静态变量,无法被继承
Person.age = 18;
//公有静态成员可被继承
Person.prototype.sex = "男";
//公有静态函数可以被继承
Person.prototype.say = function(){
alert("person2");
}
//创建子类
function Student(){
}
//继承person
Student.prototype = new Person("iwen",1);
//修改因继承导致的constructor变化
Student.prototype.constructor = Student;
//保存父类的引用
var superPerson = Student.prototype.say;
//复写父类的方法
Student.prototype.say = function(){
//调用父类的方法
superPerson.call(this);
alert("Student");
}
//创建实例测试
var s = new Student();
alert(s instanceof Person);//true
s.say();//person2 student
继承的封装函数
function extend(Child, Parent) {
var F = function(){};
F.prototype = Parent.prototype;
Child.prototype = new F();
Child.prototype.constructor = Child;
Child.uber = Parent.prototype;
}
uber意思是为子对象设一个uber属性,这个属性直接指向父对象的prototype属性。(uber是一个德语词,意思是”向上”、”上一层”。)这等于在子对象上打开一条通道,可以直接调用父对象的方法。这一行放在这里,只是为了实现继承的完备性,纯属备用性质。
方式二
相当于拷贝,通过定义的_this对象来承载想要被继承的对象,这样的话通过传递_this就可以实现继承,比上面那种好理解些
//创建父类
function Person(name,id){
//创建一个对象来承载父类所有公有东西
//也就是说_this承载的对象才会被传递给子类
var _this = {};
_this.name = name;
//这样的是不会传递下去的
this.id = id;
//承载方法
_this.say = function(){
alert("Person");
}
//返回_this对象
return _this;
}
//子类
function Student(){
//获取person的_this对象,从而模仿继承
var _this = Person("iwne",1);
//保存父类的_this引用
var superPerson = _this.say;
//复写父类的方法
_this.say = function(){
//执行父类的say
superPerson.call(_this);
alert("Student");
}
return _this;
}
var s = new Student();
s.say();
希望对大家学习javascript程序设计有所帮助。
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号