<html>
<head>
<meta charset="UTF-8"/>
<title></title>
</head>
<body>
</body>
</html>
<script type="text/javascript">
/**
* 原始做法:
* 1. 类似于vue的编写结构。
* 2. 执行的内容单一,无法复用。
* */
let obj = {
name:"张",
age:"13",
run:function(){
return this.name + this.age + "岁";
}
};
console.log(obj.run());
/**
* 工厂模式:
* 1. 将对象写入方法中,通过调用方法传参,可以实现代码的复用性。
* 2. 在调用方法时,创建不同的对象,里面的属性和方法重复创建,影响性能。
* */
function objFun(name,age){
let obj = {
name:name,
age:age,
run:function(){
return this.name + this.age + "岁啦";
}
};
return obj;
}
let one = objFun("李","14");
let two = objFun("周","16");
console.log(one.run());
console.log(two.run());
/**
* 构造函数:
* 1. 首先创建函数,函数内声明对象的属性和方法。
* 2. new实例化函数,创建对象。
* 3. 内存问题仍然没有解决,仍影响性能。
* 4. 出现新的问题,this的指向不确定,需要经常去改变this的指向。
* */
function ObjFun(name,age){
this.name = name;
this.age = age;
this.run = function(){
return this.name + this.age + "岁……";
}
}
let first = new ObjFun("冯","17");
let second = new ObjFun("吴","18");
console.log(first.run());
console.log(second.run());
/**
* 混合模式:
* 1. 将构造函数与原型结合使用。(一般将属性写在构造函数内,将公用的方法定义在原型上)
* 2. 解决了公用的方法重复创建的问题,提高了性能。
* 3. this的指向问题可以解决。
* 4. 涉及到的内容有:原型链,继承。
* */
function ObjFun1(name,age){
this.name = name;
this.age = age;
}
ObjFun1.prototype.run = function(){
return this.name + this.age + "岁。";
}
let yi1 = new ObjFun1("赵","19");
let er1 = new ObjFun1("钱","20");
console.log(yi1.run());
console.log(er1.run());
//原型链
console.log(yi1.__proto__);//相当于ObjFun1.prototype
console.log(yi1.__proto__.__proto__);//相当于Object.prototype
console.log(yi1.__proto__.__proto__.__proto__);//null
console.log(yi1.__proto__ === er1.__proto__); //true
//继承
function ObjFun2(name,age){
ObjFun1.call(this,name,age); //对属性的继承
}
// ObjFun2.prototype = new ObjFun1(); //使用时,会造成二次继承属性,影响性能
for (var i in ObjFun1.prototype) { //只是对原型的继承
ObjFun2.prototype[i] = ObjFun1.prototype[i];
}
let yi2 = new ObjFun2("孙","21");
let er2 = new ObjFun2("周","22");
console.log(yi2.run());
console.log(er2.run());
/**
* Es6中class的引入:
* 1. constructor用来声明属性和方法的调用,相当于入口文件
* 2. class声明时,与函数不同没有“()”
* 3. class中声明的方法之间没有“,”
* */
class ObjFun3 {
constructor(name,age) {
this.name = name;
this.age = age;
}
run (){
return this.name + this.age + "岁!!";
}
}
let san = new ObjFun3("吴","23");
let wu = new ObjFun3("刘","24");
console.log(san.run());
console.log(wu.run());
//继承
class Son3 extends ObjFun3 {
constructor(name,age,sex) {
super(name,age);
this.sex = sex ;
}
runs (){
return this.name + this.age + "岁了!性别:" + this.sex;
}
}
let liu = new Son3("马","25","男");
console.log(liu.run());
console.log(liu.runs());
</script>