Static and Instance Methods in JavaScript

https://abdulapopoola.com/2013/03/30/static-and-instance-methods-in-javascript/javascript

在閱讀vue示例代碼時,常常看到Vue.xx函數或者$vm.yy函數,不太清楚這二者之間有什麼區別。php

google之後發現實際上仍是有本質的區別的。vue

咱們知道javascript的繼承模型和java,php等面向對象的編程語言有很是大的差異java

js是一個弱典型的類型語言,class類並非真正的class,實際上class就是自己也是object的construct functions.咱們經過使用new constructor調用來建立新的對象,這實際上某種意義上模擬了OOP.可是請記住:js的繼承模型和傳統的javas, php是不一樣的!node

首先有static property/instance property這個機率。全部對象屬性(this.xx)都爲public的,能夠經過thisobj.xx直接訪問。固然咱們能夠經過在constructor function(也就是class類定義)中增長var關鍵字使得相應屬性變爲private的,對於這種private類型的屬性,咱們必須經過定義accessors和setters纔可以訪問。編程

//Constructor
var Person = function (name, age){
    //private properties
    var priv = {};
    
    //Public properties
    this.name = name;
    this.age = age;
    
    //Public methods
    this.sayHi = function(){
        alert('hello');
    }
}

// A static method; this method only 
// exists on the class and doesn't exist 
// on child objects
Person.sayName = function() {
    alert("I am a Person object ;)");  
};

// An instance method; 
// All Person objects will have this method
Person.prototype.setName = function(nameIn) {
    this.name = nameIn;  
}

// Tests
var per = new Person('John Doe', 22);

//Shows alert
Person.sayName();

//TypeError: Object [object Object] has no method 'sayName'
per.sayName()

//Show alert
per.sayHi();

//John Doe
per.name;

//22
per.age;

per.setName('Jane Doe');

//Jane Doe
per.name;

須要注意的是定義在類(構造函數)的屬性上的static屬性或者方法是不能在instance實例的上下文中訪問的。可是java語言在這一點上就有所不一樣,在java中靜態方法或者屬性是能夠在實例的上下文環境中訪問的。這看起來很是奇怪,由於實例objects對象中並無那個變量編程語言

這裏我引用一下java的相關說明:函數

"this

你也能夠經過對象引用的模式來訪問靜態方法,好比:google

myBike.numberOfBicycles

"

最後,咱們來看Vuejs plugin中的幾種用法,你們能夠對照上面的所謂static和instance method來看:

MyPlugin.install = function (Vue, options) {
  // 1. add global method or property
  Vue.myGlobalMethod = function () {
    // some logic ...
  }

  // 2. add a global asset
  Vue.directive('my-directive', {
    bind (el, binding, vnode, oldVnode) {
      // some logic ...
    }
    ...
  })

  // 3. inject some component options
  Vue.mixin({
    created: function () {
      // some logic ...
    }
    ...
  })

  // 4. add an instance method
  Vue.prototype.$myMethod = function (methodOptions) {
    // some logic ...
  }
}
相關文章
相關標籤/搜索