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 ...
  }
}
相关文章
相关标签/搜索