笨笨对面向对象的理解
不要惧怕不熟悉的文字,加油!
1.工厂模式
function person(name,age){
var obj = {};
obj.name = name,
obj.age = age,
obj.sayName = function(){
alert(this.name)
}
return obj
}
var person1 = person('yxy',20);
var person2 = person('yay',10);
注:工厂模式的特点:
1. 在函数中声明对象
2. 用return返回该对象
3. 直接调用函数
2.构造函数模式
function Person(name,age){
this.name = name,
this.age = age,
this.sayName = function(){
alert(this.name)
}
}
var person1 = new Person('yxy',20);
var person2 = new Person('yay',10);
注:构造函数的特点:
1.构造函数要用大驼峰 //推荐
2. 无需在构造函数中声明对象,没有return语句
3. 直接将属性和方法绑定到了this对象上
4. 使用new调用
此时,person1和person2的构造器(constructor)都指向了Person,也指向Object,
person1 instanceof Person;//true
person2 instanceof Person;//true
person1 instanceof Object;//true
person2 instanceof Object;//true
有没有发现在构造函数的模式里,sayName的方法被创建了两次,每new一个实例的时候,就创建了一次sayName,so...
function Person(name,age){
this.name = name,
this.age = age,
this.sayName = sayName;
}
//将sayName 作为全局方法
function sayName(){
alert(this.name);
}
var person1 = new Person('yxy',20);
var person2 = new Person('yay',10);
person1.sayName == person2.sayName;//true true就表示被执行了一次哦~
3.原型模式
由于在全局作用域中定义的sayName函数仅仅是被某个对象调用,非常小题大作,so...可以用原型模式来解决
function Person(){
}
Person.prototype = {
constructor:Person,//由于重写了构造函数的原型后,原有的constructor被重写了,所以需要再给它指向一下Person
name:'yxy',
age:20,
sayName:function(){
alert(this.name)
}
}
var person1 = new Person();
var person2 = new Person();
注:原型模式的特点:
1. 将属性和方法都赋到原型对象上
4.组合模式(构造函数模式+原型模式)
上述的原型模式中,如果其中某个属性是引用类型,创建的实例会共享这些属性,加一个friends属性,如:
Person.prototype = {
constructor:Person,
name:'yxy',
age:20,
friends:['Hccc1','Zh','Y'],
sayName:function(){
alert(this.name)
}
}
var person1 = new Person();
var person2 = new Person();
person1.friends.push('little A');
console.log(person1.friends);//["Hccc1", "Zh", "Y", "Li"]
console.log(person2.friends);["Hccc1", "Zh", "Y", "Li"]
发现了吧,属性被共享了,解决办法就是用组合模式(最好的模式):
function Person(name,age){
this.name = name;
this.age = age;
this.friends = ['Hccc1','Zh','Y'];
}
Person.prototype = {
constructor:Person,
sayName:function(){
alert(this.name);
}
}
var person1 = new Person('yxy',20);
var person2 = new Person('yay',10);
console.log(person1.friends);// ["Hccc1", "Zh", "Y"]
console.log(person2.friends);// ["Hccc1", "Zh", "Y"]
person1.friends.push('AAA');
console.log(person1.friends);// ["Hccc1", "Zh", "Y", "AAA"]
console.log(person2.friends);// ["Hccc1", "Zh", "Y"]
棒!
笨鸟飞呀飞~
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?