面向对象(Object Oriented Programming):使用对象时,只关注对象提供的功能,不关注其内部细节。不了解原理的情况下,会使用功能
对象:对象是一个整体,对象是JavaScript的基本数据类型。除了字符串,数字,true,false,null和undefind之外,JavaScript的值都是对象。对外提供一些操作。不了解内部结构,知道表面的各种操作。
面向对象是一种通用思想,并非只有编程中能用,任何事情都可以用
面向对象编程(OOP)的特点
-抽象:抓住核心问题 把主要的特征、问题相关的特征抽出来
-封装:不考虑内部实现,只考虑功能使用
-继承:从已有对象上,继承出新的对象
--多重继承 同时继承多个对象的特性
--多态
对象的组成
-方法——函数:过程、动态的
-属性——变量:状态、静态
var a=12;
alert(a);
var arr =[1,2,3,4,5,6];
arr.a=12;
function aaa(){
}
arr.aaa = function (){
}
aaa();
arr.aaa();
arr.show = function (){
}
arr.show();
function show(){
}
show();
demo001
var obj001 = new Object();
obj001.name ='nainai';
obj001.qq ='39456238';
obj001.showName = function(){
alert('My name :'+this.name);
}
obj001.showQq = function(){
alert('My qq :'+this.qq);
}
obj001.showName();
obj001.showQq();
封装成函数
工厂方式
什么是工厂
-原料
-加工
-出厂
工厂方式
-用构造函数创建一个类
-什么是类、对象(实例):模具和零件
问题
-没有new
-函数重复定义
加上new
-偷偷做了两件事
-替你创建了一个空白对象
-替你返回了这个对象
new和this
function createObj(name,qq){
var obj001 = new Object();
obj001.name =name;
obj001.qq =qq;
obj001.showName = function(){
alert('My name :'+this.name);
}
obj001.showQq = function(){
alert('My qq :'+this.qq);
}
return obj001;
}
var obj = createObj('sama','616010');
obj.showName();
obj.showQq();
var obj2 = createObj('sansan','37690');
obj2.showName();
obj2.showQq();
1,没有new
function show(){
alert(this);
}
show();
new show();
function createObj(name,qq){
this.name =name;
this.qq =qq;
this.showName = function(){
alert('My name :'+this.name);
}
this.showQq = function(){
alert('My qq :'+this.qq);
}
}
var obj =new createObj('sama','616010');
obj.showName();
obj.showQq();
var obj2 =new createObj('sansan','37690');
obj2.showName();
obj2.showQq();
var arrf01 = new Array(1,7,9,12,15,18,20);
arrf01.sum = function(){
var res = 0,i,len=this.length;
for(i=0;i<len;i++){
res+=this[i];
}
return res;
}
alert(arrf01.sum());
var arrf02 = new Array(2,6,9,12,15,18,30);
Array.prototype.sum = function(){
var res = 0,i,len=this.length;
for(i=0;i<len;i++){
res+=this[i];
}
return res;
}
alert(arrf01.sum());
alert(arrf02.sum());
原型
CSS中 js
class 一次给一组元素加样式 放相同的 原型,一次给一组元素加 放相同
行间样式 一次给一个元素加样式 放不同 给对象加东西
<div class="box" style="color:red"></div>
<div class="box"></div>
<div class="box"></div>
原型——prototype
-什么是原型
-原型是class,修改他可以影响一类元素
-在已有对象中加入自己的属性、方法
-原型修改对已有对象的影响
为Array添加sum方法
-给对象添加方法,类似于行间样式
-给原型添加方法,类似于class
原型的小缺陷
-无法限制覆盖
类、对象
类:模子 用于生成别的东西
对象:成品 具备实际功能
var arrf01 = new Array(1,7,9,12,15,18,20);
2,函数重复
原型用到面向对象
在构造函数加属性,在原型加方法
function CreateObj(name,qq){
this.name =name;
this.qq =qq;
}
CreateObj.prototype.showName = function(){
alert('My name :'+this.name);
}
CreateObj.prototype.showQq = function(){
alert('My qq :'+this.qq);
}
var obj = new CreateObj('sama','616010');
obj.showName();
obj.showQq();
var obj2 = new CreateObj('sansan','37690');
obj2.showName();
obj2.showQq();
用混合方式构造对象
混合的的构造函数/原型方式
Mixed Constructor Function/Prototype Method
原则
构造函数:加属性
原型:加方法
对象命名规范
类名首字母大写 Date Array