以下两个声明有什么区别?
Class.method = function () { /* code */ }
Class.prototype.method = function () { /* code using this.values */ }
可以将第一条语句视为静态方法的声明,将第二条语句视为实例方法的声明吗?
以下两个声明有什么区别?
Class.method = function () { /* code */ }
Class.prototype.method = function () { /* code using this.values */ }
可以将第一条语句视为静态方法的声明,将第二条语句视为实例方法的声明吗?
是的,第一个函数与该构造函数的对象实例没有关系,您可以将其视为“静态方法”。
在 JavaScript 中,函数是一等对象,这意味着您可以像对待任何对象一样对待它们,在这种情况下,您只需向函数对象添加一个属性。
第二个函数,当您扩展构造函数原型时,它将可用于所有使用new关键字创建的对象实例,并且该函数(this关键字)内的上下文将引用您调用它的实际对象实例。
考虑这个例子:
// constructor function
function MyClass () {
  var privateVariable; // private member only available within the constructor fn
  this.privilegedMethod = function () { // it can access private members
    //..
  };
}
// A 'static method', it's just like a normal function 
// it has no relation with any 'MyClass' object instance
MyClass.staticMethod = function () {};
MyClass.prototype.publicMethod = function () {
  // the 'this' keyword refers to the object instance
  // you can access only 'privileged' and 'public' members
};
var myObj = new MyClass(); // new object instance
myObj.publicMethod();
MyClass.staticMethod();
是的,第一个static method也称为class method,而第二个是instance method。
考虑以下示例,以更详细地了解它。
在 ES5 中
function Person(firstName, lastName) {
   this.firstName = firstName;
   this.lastName = lastName;
}
Person.isPerson = function(obj) {
   return obj.constructor === Person;
}
Person.prototype.sayHi = function() {
   return "Hi " + this.firstName;
}
上面代码中,isPerson是静态方法,而sayHi是 的实例方法Person。
下面,是如何从Person构造函数创建对象。
var aminu = new Person("Aminu", "Abubakar");
使用静态方法isPerson。
Person.isPerson(aminu); // will return true
使用实例方法sayHi。
aminu.sayHi(); // will return "Hi Aminu"
在 ES6 中
class Person {
   constructor(firstName, lastName) {
      this.firstName = firstName;
      this.lastName = lastName;
   }
   static isPerson(obj) {
      return obj.constructor === Person;
   }
   sayHi() {
      return `Hi ${this.firstName}`;
   }
}
看看如何使用static关键字来声明静态方法isPerson。
创建Person类的对象。
const aminu = new Person("Aminu", "Abubakar");
使用静态方法isPerson。
Person.isPerson(aminu); // will return true
使用实例方法sayHi。
aminu.sayHi(); // will return "Hi Aminu"
注意:这两个例子本质上是一样的,JavaScript 仍然是一种无类语言。在class中介绍ES6主要是在现有的基于原型的继承模型是语法糖。
当您创建多个 MyClass 实例时,您在内存中仍然只有一个 publicMethod 实例,但是在 privilegedMethod 的情况下,您最终将创建大量实例,而 staticMethod 与对象实例没有关系。
这就是原型节省内存的原因。
另外,如果你改变了父对象的属性,如果子对象的相应属性没有改变,它就会被更新。
对于视觉学习者,在定义函数时没有 .prototype
ExampleClass = function(){};
ExampleClass.method = function(customString){
             console.log((customString !== undefined)? 
                          customString : 
                          "called from func def.");}
ExampleClass.method(); // >> output: `called from func def.`  
var someInstance = new ExampleClass();
someInstance.method('Called from instance');
    // >> error! `someInstance.method is not a function`  
使用相同的代码,如果.prototype添加,  
ExampleClass.prototype.method = function(customString){
             console.log((customString !== undefined)? 
                          customString : 
                          "called from func def.");}
ExampleClass.method();  
      // > error! `ExampleClass.method is not a function.`  
var someInstance = new ExampleClass();
someInstance.method('Called from instance');
                 // > output: `Called from instance`
为了更清楚,
ExampleClass = function(){};
ExampleClass.directM = function(){}  //M for method
ExampleClass.prototype.protoM = function(){}
var instanceOfExample = new ExampleClass();
ExampleClass.directM();     ✓ works
instanceOfExample.directM();   x Error!
ExampleClass.protoM();     x Error!
instanceOfExample.protoM();  ✓ works
****注意上面的例子,someInstance.method() 不会被执行,
ExampleClass.method() 导致错误并且执行不能继续。
但为了说明和易于理解,我保留了这个序列。****
生成的结果chrome developer console&
单击上面的 jsbin 链接以逐步执行代码。
使用+切换评论部分JS Bin
ctrl/
A. 静态方法:
      Class.method = function () { /* code */ }
method()这是添加到另一个函数(此处为 Class)的函数属性。Class.method();new Class()) 来访问 method()。因此,您可以将其称为静态方法。B. 原型方法(所有实例共享):
     Class.prototype.method = function () { /* code using this.values */ }
method()这是添加到另一个函数原型(此处为 Class.prototype)的函数属性。new Class())。ClassC. 类方法(每个实例都有自己的副本):
   function Class () {
      this.method = function () { /* do something with the private members */};
   }
method()这是在另一个函数(此处为 Class)中定义的方法。Class.method();new Class()为 method() 访问创建一个对象/实例 ( )。new Class())。例子:
    function Class() {
        var str = "Constructor method"; // private variable
        this.method = function () { console.log(str); };
    }
    Class.prototype.method = function() { console.log("Prototype method"); };
    Class.method = function() { console.log("Static method"); };
    new Class().method();     // Constructor method
    // Bcos Constructor method() has more priority over the Prototype method()
    // Bcos of the existence of the Constructor method(), the Prototype method 
    // will not be looked up. But you call it by explicity, if you want.
    // Using instance
    new Class().constructor.prototype.method(); // Prototype method
    // Using class name
    Class.prototype.method(); // Prototype method
    // Access the static method by class name
    Class.method();           // Static method