JavaScript_day18

day18内容

复习
面向对象的编程设计
批量创建对象
1.工厂模式
普通函数内部返回一个Object类型对象,对象有属性和方法。如果多次调用方法,产生多个对象。
function createPerson(name,age,gender){
return {
name:name,
age:age,
gender:gender
}
}
createPerson(‘zhangsan’,1,‘male’)
无法区分类型,都是Object
2.构造函数模式
创建一个构造函数。该构造函数使用new关键字调用。
new关键字作用
1)创建一个实例
2)构造函数内this–>该实例
3)执行构造函数内的代码
4)返回该实例
function sayName(){
console.log(‘hello’);
}
function Person(name,age,gender){
this.name = name;
this.age = age;
this.gender = gender;
this.sayName = sayName;
}
关于方法内存浪费或者封装不完全。
3)原型模式
将对象内所有的内容都放到构造函数的原型对象中。在原型对象中的都是共享的。
function Person(){}
/Person.prototype.name = ‘’;
Person.prototype.age = ‘’;
Person.prototype.gender = ‘’;
Person.prototype.friends = [];
Person.prototype.sayName = function(){};
/
Person.prototype = {
constructor:Person,
name:’’,
age:’’,
gender:’’,
friends:’’,
sayName:function(){}
};
对于方法是极好的,对于属性的引用类型的值使用不友好。
4)构造函数+原型模式
将实例各自拥有的属性和方法放到构造函数中,将实例共有的属性和方法放到原型对象中。
function Person(name,age,gender){
this.name = name;
this.age = age;
this.gender = gender;
this.friends = [];
}
Person.prototype = {
constructor:Person,
sayName:function(){
}
};
继承
1)原型链继承
继承父构造函数原型对象中的属性和方法。
将子构造函数的原型对象指向修改为父构造函数的实例。
function Animal(){}
Animal.prototype = {};
function Cat(){}
Cat.prototype = new Animal();
Cat.prototype.constructor = Cat;
2)经典继承
在子构造函数内调用父构造函数运行
function Animal(color){
this.color = color;
}
function Cat(color,ear){
Animal.call(this,color);
this.ear = ear;
}
3)组合继承(原型链+经典继承)
function Animal(color){
this.color = color;
}
Animal.prototype = {};
function Cat(color,ear){
Animal.call(this,color);
this.ear = ear;
}
Cat.prototype = new Animal();
Cat.prototype.constructor = Cat;

DOM 文档对象模型
注意浏览器的兼容性
原生js操作html节点
< div>hello</ div>
对节点进行增删改查
Node类型 节点
文档节点 Document类型 document
元素节点 Element类型 < div id=“one”>hello</ div>
属性节点 id=“one”
文本节点 Text类型 hello
注释节点 Comment类型 < !–注释–>

发布了40 篇原创文章 · 获赞 1 · 访问量 703

猜你喜欢

转载自blog.csdn.net/hanmiao12345/article/details/105642415