【面向过程】
每一个过程都会去做
【面向对象】
思想,写程序的方法
1、什么是对象
都是独立的个体
2、什么是面向对象
咱们只关心怎么使用,不去关系他的内部是如何实现的
arr.push()
3、怎么创建一个对象
var arr=[];
arr.length 属性
arr.push() 方法
对象身上都有属性和方法
属性/变量
变量:自由的个体,没有约束
属性:依附于对象身上。
方法/函数
函数:自由的个体,没有约束
方法:依附于对象身上。
this:当前触发事件的对象(元素)
当前的方法属于谁,this就是谁
var first=[];
first.a=1;
first.show=function(){
alert(1);
}
var oDate=new Date();
var oDate1=new Date();
原材料
数组
json
事件对象
var obj=new Object(); 造一个空白的对象
new的问题
new Date();
new Array();
new Function();
new JSON();
new Object();
show()
普通函数
构造函数
首字母大写 主要是和普通函数做区分
构造函数也是函数,主要是因为功能起了个名字
加new有什么特点
1、他会在函数内部自动创建一个空白对象,并且把this指向对象
2、最后他会把this(对象),自动返回出去
面向对象的特点
封装
多态
继承
原型
面向对象(ES6之前真正的面向对象)
function CreateObject(name,age){
//构造函数身上加属性
this.name=name;
this.age=age;
}
//原型身上加方法
CreateObject.prototype.showName=function(){
return this.name
}
var p1=new CreateObject('小明',13);
alert(p1.showName())
例子:
1、arr.chaAt()
2、str.trim(); //去除字符串收尾空格
reg=/^\s+|\s+$/g;
3、oDate.getCnDay() // 返回的是 ’星期一‘
原型:
1、面向对象
2、扩展系统函数
类:在js中类就是构造函数,作用就是造对象,他就像一个模子
实例:通过new这种构造函数返回的结果,也就是造出来的对象
面向对象特性:
封装(前端不用太考虑)
把一个事物的核心抽象出来
继承 ***
在ES6之前的继承,都是通过prototype来实现的
多态(前端不用太考虑)
一个孩子继承了多个亲人的特性
面向对象中的一些小细节小问题(不常用,都在面试里出现)
typeof 检测数据类型
instanceof 检测一个物体的数据类型 检测一个东西和另一个有没血缘关系
constructor 某个东西是不是通过某个构造器造出来了
可以理解为直接的父亲
题:
第一大题
alert(typeof Date) //function
alert(typeof Function); //function
alert(Function instanceof Object) //true
alert(Object instanceof Function)//true
alert(Function instanceof Function)//true
alert(Object instanceof Object) //true
第二道题
alert(arr instanceof Array); //true
alert(Array instanceof Function)//true
alert(arr instanceof Function) //false
第三题
Object.prototype.a=12;
var arr=[1,2,3];
//alert(arr.a) //12
//var a=5;
//var a=new Number(5)
//alert(a.a);
//alert(a instanceof Object);
//var str='abc';
var str=new String('abc')
//alert(str.a)
alert(str instanceof Object)
简写的基本类型,Object不认,除非new出来
包装类
第四题(this)
function show(){
alert(this)
}
//show(); //window
//new show();//object
var arr=[1,2,3];
arr.show=show;
//arr.show();//1,2,3
//new arr.show();//object
document.onclick=show;//document
//new document.onclick();//object
//setTimeout(show,100);//window
//setTimeout(arr.show,100);//window
//setTimeout(document.onclick,200); //一上来是window,点击的时候是document
//setTimeout(new document.onclick,200);//一上来object,点击的时候是document
setTimeout(new arr.show,100)//object
this是有优先级:
new -> object
定时器 -> window
事件 -> 事件对象
方法 -> 当前方法的对象
其他
面向对象写法:
1、把所有的变量放到构造函数中
2、把所有的函数放到原型上
3、始终保证this在构造身上
包一层把正确的this放进去
网友评论