首页 > 代码库 > JavaScript: Class.method vs Class.prototype.method
JavaScript: Class.method vs Class.prototype.method
在stack overflow中看到一个人回答,如下
// constructor functionfunction 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 instanceMyClass.staticMethod = function () {}; //first functionMyClass.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 instancemyObj.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 this
keyword) 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