网络编程
位置:首页>> 网络编程>> JavaScript>> javascript中的面向对象

javascript中的面向对象

作者:阁主乄  发布时间:2024-04-18 10:54:33 

标签:javascript,面向对象

相信大家对javascript中的面向对象写法都不陌生,那还记得有几种创建对象的写法吗?相信大家除了自己常写的都有点模糊了,那接下来就由我来帮大家回忆回忆吧!

1. 构造函数模式

通过创建自定义的构造函数,来定义自定义对象类型的属性和方法。


function cons(name,age){
this.name = name;
this.age = age;
this.getMes = function(){
 console.log(`my name is ${this.name},this year ${this.age}`);
}
}
var mesge = new cons('will',21);
mesge.getMes();

2. 工厂模式

该模式抽象了创建具体对象的过程,用函数来封装以特定接口创建对象的细节


function cons(name,age){
var obj = new Object();
obj.name = name;
obj.age = age;
obj.getMes = function(){
 console.log(`my name is ${this.name},this year ${this.age}`);
}
return obj;
}
var mesge = cons('will',21);
mesge.getMes();

3. 字面量模式

字面量可以用来创建单个对象,但如果要创建多个对象,会产生大量的重复代码


var cons = {
name: 'will',
age : 21,
getMes: function(){
 console.log(`my name is ${this.name},this year ${this.age}`);
}
}
cons.getMes();

4. 原型模式

使用原型对象,可以让所有实例共享它的属性和方法


function cons(){
cons.prototype.name = "will";
cons.prototype.age = 21;
cons.prototype.getMes = function(){
 console.log(`my name is ${this.name},this year ${this.age}`);
}
}

var mesge = new cons();
mesge.getMes();

var mesge1 = new cons();
mesge1.getMes();
console.log(mesge.sayName == mesge1.sayName);//true

5. 组合模式

最常见的方式。构造函数模式用于定义实例属性,而原型模式用于定义方法和共享的属性,这种组合模式还支持向构造函数传递参数。实例对象都有自己的一份实例属性的副本,同时又共享对方法的引用,最大限度地节省了内存。该模式是目前使用最广泛、认同度最高的一种创建自定义对象的模式


function cons(name,age){
this.name = name;
this.age = age;
this.friends = ["arr","all"];
}
cons.prototype = {
getMes : function(){
 console.log(`my name is ${this.name},this year ${this.age}`);
}
}
var mesge = new cons("will",21);
var mesge1 = new cons("jalo",21);
console.log(mesge.friends);
mesge.friends.push('wc'); //还可以操作数组哈O(∩_∩)O!
console.log(mesge.friends);
console.log(mesge1.friends);
mesge.getMes();
mesge1.getMes();
console.log(mesge.friends === mesge1.friends);
console.log(mesge.sayName === mesge1.sayName);

最后在告诉你个秘密,ES6引入了类(Class),让对象的创建、继承更加直观了


// 定义类

class Cons{
constructor(name,age){
 this.name = name;
 this.age = age;
}
getMes(){
 console.log(`hello ${this.name} !`);
}
}
let mesge = new Cons('啦啦啦~',21);
mesge.getMes();

在上面的代码片段里,先是定义了一个Cons类,里面还有一个constructor函数,这就是构造函数。而this关键字则代表实例对象。

而继承可以通过extends关键字实现。


class Ctrn extends Cons{
constructor(name,anu){

super(name); //等同于super.constructor(x)
 this.anu = anu;
}
ingo(){
 console.log(`my name is ${this.name},this year ${this.anu}`);
}
}
let ster = new Ctrn('will',21);
ster.ingo();
ster.getMes();

来源:http://www.cnblogs.com/zhengjialux/p/6635916.html

0
投稿

猜你喜欢

手机版 网络编程 asp之家 www.aspxhome.com