javascript中的面向对象

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

1. 构造函数模式

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

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. 工厂模式

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

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. 组合模式

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

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关键字则表明实例对象。prototype

而继承能够经过extends关键字实现。code

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();

好了,此次的分享就到这了,喜欢的朋友能够收藏哦(关注我也是能够滴O(∩_∩)O)!!!对象

相关文章
相关标签/搜索