对象:
存在一种键(属性):值映射关系的集合
Javascript里面的面向对象:
封装、继承、多态(JS里面不明显,父亲调用儿子不明显)
Js(ES5)里面没有"class"的概念,用函数
(构造函数,个人感觉很诡异,构造函数可
以当成类)来代替"class"。
示例代码1:
//使用构造函数
function Student(name,age,stu_id){
this.stu_id=stu_id;
this.age=age;
this.name=name;
}
Student.prototype.say=function(){
alert(this.name);
alert(this.age);
alert(this.stu_id);
}
var stu=new Student("小明",18,35);
stu.say();
原型、构造函数、实例。
JS里面的"class"使用构造函数进行构建,构造函数
里面有一个属性prototype指向另外一个对象(原型对象)
这个原型对象里面包含了一个constructor属性(指针)指向
构造函数以及其它从Object对象继承过来的一些属性,这些属性
是共享的,,任何一个实例获取的属性以及方法
都是来自这个共享的原型对象的。
三者数据结构:链表如图:
原型链(继承)
核心:将儿子的原型对象作为实例去获取父亲的原型对象,并且保证自己也是个原型对象
示例代码2:
//父类
function Person(name,age){
this.name=name;
this.age=age;
}
Person.prototype.say1=function(){
alert(this.name);
alert(this.age);
}
//子类
function Student(name,age,stu_id){
this.stu_id=stu_id;
Person.call(this,name,age);
}
//Student原型指向对方的原型
Student.prototype=new Person();
//同时得保证自己也是一个构造函数的原型
Student.prototype.constructor=Student;
Student.prototype.say2=function(){
alert(this.stu_id);
}
var stu=new Student('xuhacker',18,36);
stu.say1();
stu.say2();
ES6里面的面向对象和继承
1.有了class关键字
2.每个类里面有了constructor构造方法(声明相关属性)
3.方法单独跟在后面
4.继承必须要有extends和super关键字
ps:(感觉es6和python里面的面向对象语法几乎一模一样)
示例代码3:
//es6里面的面向对象
class Person{
constructor(name,age){
this.name=name;
this.age=age;
}
say(){
alert(this.name);
alert(this.age);
}
}
let p=new Person('xuhacker',18);
p.say();
//es6 面向对象继承
class Student extends Person{
constructor(name,age,stu_id){
super(name,age);
this.stu_id=stu_id;
}
say2(){
alert(this.stu_id)
}
}
let stu=new Student('xuhacker',18,11);
stu.say()
stu.say2()