1-js的组成
**1.DOM-----操作标签
2.BOM-----操作浏览器
3.ECMAScript-----语法类:函数,对象...
**js不是面向对象,基于对象****
2-函数的作用
具有封装性
3-基本对象的创建
var student={
name:'王大陆',
age:25,
eat:function(){
console.log('晚上吃点什么');
}
}
console.log(student);
student.eat();
4-工厂的方式创建对象
function Student(name,age){
return{
name:name,
age:age,
eat:function(){
console.log('晚上吃点什么');
}
}
}
var stud1=Student('张三',25)
var stud2=Student('李四',26)
stud1.eat()
stud2.eat()
5-构造函数的方式
function Product(title,price){
this.title=title;
this.price=price;
this.buy=function(){
console.log('您确认需要购买'+this.title+'吗');
}
}
var Pro1=new Product('电风扇',399);
Pro1.buy();
var Pro2=new Product('微波炉',299);
Pro2.buy();
**构造函数的不足:
正常情况下,如京东购物,不管是哪一个商品。执行购买方式应该都是一样的,但是实际情况就是实例化对象的时候会实例化两次,这个时候商品在内存中都会有同样的购买方法,造成内存资源浪费**
6-构造函数+原型的方式
**每一个构造函数都有一个prototype的属性,该属性所有的方法和属性都能被构造函数继承**
function Product(title,price){
this.title=title;
this.price=price;
this.buy=function(){
console.log('您确认需要购买'+this.title+'吗');
}
}
var Pro1=new Product('电风扇',399);
Pro1.buy();
var Pro2=new Product('微波炉',299);
Pro2.buy();
console.log(Pro1.buy==Pro2.buy);
function BoxChange(size,color,bgc){
this.size=size,
this.color=color,
this.bgc=bgc
}
BoxChange.prototype.changesize=function(){
console.log('你改变了盒子的大小吗?');
}
var box1=new BoxChange('大小','颜色','背景色')
box1.changesize();
var box2=new BoxChange('大小','颜色','背景色')
box2.changesize();
var box3=new BoxChange('大小','颜色','背景色')
box3.changesize();
console.log(box1.changesize==box2.changesize);
function Product(title,price){
this.title=title;
this.price=price;
this.alert=function(){
console.log('你确定需要购买'+this.title+'吗');
}
}
Product.prototype.buy=function (){
console.log('购买');
}
Product.prototype.joinCar=function (){
console.log('原有加入购物车');
}
var pro1=new Product('无人机',399);
pro1.buy();
console.log(pro1.__proto__==Product.prototype);
pro1.__proto__.joinCar=function(){
console.log('这是修改以后的加入购物车方式');
}
pro1.joinCar();
console.log(pro1.hasOwnProperty('alert'));
console.log(pro1.hasOwnProperty('buy'));
console.log(pro1.hasOwnProperty('joinCar'));
console.log(pro1 instanceof Product);
总结
1、js的组成
2、基本对象------如果有n多实例化对象,写起来比较繁琐
3、工厂的方式创建对象------基于基本对象的基础之上升级
4、构造函数------
5、构造函数+原型方式
6、构造函数的prototype属性(解决内存浪费问题)
7、__proto __:修改构造函数prototype属性的方法
8.、hasOwnProperty:判断是否是原构造函数的方法
9、constructor:判断该方法是什么方式创建的
此方法如果重写prototype方法时会丢失原有的constructor属性
10、a instanceof b ------最常用的判断方法