JS是web的编程语言,轻量可插入html页面的编程代码。
JS不是真的面向对象(OOP)语言,他是基于对象的语言,所有对象都是由浏览器提供给用户,直接使用即可;所以JS面向对象其实就是对Object(对象)的解读。
特点:抽象(抓住问题核心);
封装(只考虑功能的使用,不考虑内部实现);
继承(从已有对象上,继承出新的对象)。
对象:由方法和属性组成;
类:制造者(构造函数),用于初始化数据,添加属性成员
父类和子类(基类和派生类)
A、JS无类的概念,在JS中常称为父对象、子对象、基对象、派生对象
B、父类又称基类,子类又称派生类
l 封装
一、生成实例对象的原始模式
eg:
function Point(name,sex){
return{
name:name,
sex:sex
}
}
然后生成实例对象调用函数:
var point1=Point("天天","男");
var point2=Point("空空","女");
point1和point2没有内在的联系,不能反映出他们是同一个原型对象的实例。
二、构造函数模式
构造函数”:就是普通的函数,内部使用了this变量。对构造函数使用了new运算符就能生成实例,并且this变量会绑定在实例对象上。
eg:
function Point(name,sex){
this.name=name;
this.sex=sex;
this.type="学生";
this.learn=function(){console.log("语言")};
}
然后生成实例对象:
var point1=new Point("天天","男");
var point2=new Point("空空","女");
console.log(point1.name);//天天
console.log(point1.sex);//男
console.log(point1.type);//学生
console.log(point1.learn());//语言
point1和point2都含有一个constructor属性,指向他们的构造函数。
console.log(point1.constructor==Point);//true
console.log(point2.constructor==Point);//true
Javascript还提供了一个instanceof运算符,验证原型对象与实例对象之间的关系
console.log(point1 instanceof Point); //true
console.log(point2 instanceof Point); //true
弊端:每一个实例对象,type属性和learn()方法都是一样的内容,每一次 生成一个实例,都会为重复内容多占用一些内存。不环保,不效率。
console.log(point1.learn==point2.learn); //false
三、Prototype模式
每一个构造函数都有一个prototype属性指向另一个对象,这个对象的所有属性和方法,都会被构造函数的实例继承。
eg:
function Point(name,sex){
this.name=name;
this.sex=sex;
}
Point.prototype.type="学生";
Point.prototype.learn=function(){console.log("语言")};
然后生成实例对象:
var point1=new Point("天天","男");
var point2=new Point("空空","女");
console.log(point1.type);//学生
console.log(point1.learn());//语言
这时所有实例的type和learn()方法,都是同一个内存地址,指向prototype对象,提高运行效率。
console.log(point1.learn==point2.learn); //true
四、Prototype模式的验证方法
4.1、isPrototypeOf()
用来判断,某个proptotype对象和某个实例之间的关系
console.log(Point.prototype.isPrototypeOf(point1)); //true
console.log(Point.prototype.isPrototypeOf(point2)); //true
4.2、hasOwnProperty()