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

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

《javascript中的面向对象》

    原文作者:阁主
    原文地址: https://segmentfault.com/a/1190000008864363
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞