对象
// 创建对象且添加属性赋值
var student = new Object();
student.name="1";
student.showname1=function(){
alert(student.name)
}
student.showname1();
// 使用字面量赋值创建对象
var comterput={
name1:"1",
showname2:function(){
console.log(this.name1)
}
}
comterput.showname2();
简单工厂模式
工厂模式就是一种常用的用来创建对的设计模式
将创建对象的逻辑封装到一个函数中
<script>
function gonchangmoshi(name,age,email,hobby){
var p=new Object();
p.name=name;
p.age=age;
p.email=email;
p.hobby=hobby;
p.show=function(){
console.log(this.name);
}
return p;
}
// 通过 person1 变量,可以访问和操作对象 p 的属性和方法 毕竟返回了个对象
var person1=gonchangmoshi("张三",18,"zhangshan@qq.com","打球")
person1.show();
</script>
构造函数
<script>
function Student(name,age,email,hobby){
this.name=name;
this.age=age;
this.email=email;
this.hobby=hobby;
this.show=function(){
console.log(this.name);
}
}
var stu1=new Student("张三",18,"zhangshan@qq.com","打球");
stu1.show();
</script>
使用构造函数大大减少重复代码
不同之 处:
没有显示的创建对象
直接将属性和方法赋值this
没有返回语句
!!!需注意构造函数名字开头需大写 非构造函数开头小写 为了就是能够区分ECMAscript的函数
constructor判断实例化的对象是不是为你想判断的对象
这个函数的不足:那就是每次实例化调用show方法时 都不是同一个实例 (将show方法放成公共的)
构造函数升级版
<script>
function Student(name,age,email,hobby){
this.name=name;
this.age=age;
this.email=email;
this.hobby=hobby;
//show是一个方法 将show1的东西搞到show中
this.show=show1;
}
function show1(){
console.log(this.name)
}
var stu1=new Student("张三",18,"zhangshan@qq.com","打球");
stu1.show();
</script>
不足之处:定义成公共的是方便了每个对象的调用使用 不过如果对象需要更多的方法 那岂不是要创建好多方法 这样子显然不现实 为了解决这个问题 原型对象诞生了!
原型对象 prototype
原型是什么?
原型是一个属性也是一个对象
原型的作用是什么?
可以共享方法
把那些不变的方法直接定义到原型对象上
构造函数和原型中this都指向实例的对象
原型对象就是可以让所有的对象共享到他的属性和方法 比如往期稿子中的内置对象Date为例
Date对象可用的方法都是来源于其原型对象Date.prototype
js展开运算符(…)
实例对象可以访问原型靠里面的属性(proto)指向原型对象
语法:
构造函数.prototype.新属性或方法
<script>
function Student(){
}
Student.prototype.name="张三";
Student.prototype.age=18;
Student.prototype.email="zhangshan@qq.com";
Student.prototype.hobby="打球";
Student.prototype.show=function(){
console.log(this.name);
}
var stu1=new Student();
stu1.show();
var stu2=new Student();
stu2.show();
</script>
在JavaScript中,我们创建一个函数A(就是声明一个函数), 那么浏览器就会在内存中创建一个对象B,而且每个函数都默认会有一个属性 prototype 指向了这个对象( 即:prototype的属性的值是这个对象 )。这个对象B就是函数A的原型对象,简称函数的原型。这个原型对象B 默认会有一个属性 constructor 指向了这个函数A ( 意思就是说:constructor属性的值是函数A )。
原型链
假如一个原型对象等于另外一个类型的实例 ,另外一个类型的原型对象又等于另外一个类型的示例
子级的prototype.__proto__指向父级的prototype !!!
伪造对象或者经典继承
function Car(brand, color) {
this.Brand = brand
this.Color = color
this.getBrand = function () {
console.log("品牌:" + this.Brand)
}
this.getColor = function () {
console.log("颜色:" + this.Color)
}
}
function Truck(place,brand, color) {
//call 父级替换成当前对象(自己理解的)
Car.call(this, brand, color)
this.Place = place
this.getPlace = function () {
console.log("产地:" + this.Place)
}
}
var t = new Truck("1","2","3");
//经典继承 这种方式只能访问到实例属性方法 不能访问到原型对象
t.getBrand();
t.getColor();
t.getPlace();
这时候经典继承继承不了原型对象 只能使用组合继承 解决了这个问题 极大优化了以上代码问题
组合继承
这样子就可以解决访问到原型对象
apply和call方法的区别 apply的传参是数组 而call可以一个接着一个传字符串参数