JavaScript: Class.method vs Class.prototype.method

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了JavaScript: Class.method vs Class.prototype.method相关的知识,希望对你有一定的参考价值。


在stack overflow中看到一个人回答,如下      

// 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 () {};   //first function

MyClass.prototype.publicMethod = function () {       //second 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();

 

 

Yes, the first function has no relationship(有关) with an object instance of that constructor function, you can consider it like a ‘static method‘.

In javascript functions are first-class objects, that means you can treat them just like any object, in this case, you are only adding a property to the function object.

The second function, as you are extending the constructor function prototype, it will be available to all the object instances created with the new keyword, and the context within that function (the thiskeyword) will refer to the actual object instance where you call it.

简单理解:(MyClass.staticMethod ) 构造函数也是对象,可以在其上进行添加属性或方法,添加在其上的与对象实例无关

(MyClass.prototype.publicMethod)   这是扩展构造函数原型对象,用来与new关键字来创建所有对象实例。在函数中,this 指向的是实例对象。

 

参考地址:

 

以上是关于JavaScript: Class.method vs Class.prototype.method的主要内容,如果未能解决你的问题,请参考以下文章

javascript Class.method vs Class.prototype.method(类方法和对象方法)

为啥有些人在通信中使用 Class#method 而不是 Class.method?

错误索引方法“Class.Method”无法将参数“log”绑定到类型 TraceWriter

Python OOP-static method,class method and instance method

ABAP中Class/method对应program name获取

017: class, objects and instance: class method