JavaScript:Class.method 与 Class.prototype.method [英] JavaScript: Class.method vs. Class.prototype.method

查看:30
本文介绍了JavaScript:Class.method 与 Class.prototype.method的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下两个声明有什么区别?

What is the difference between the following two declarations?

Class.method = function () { /* code */ }
Class.prototype.method = function () { /* code using this.values */ }

可以将第一条语句视为静态方法的声明,将第二条语句视为实例方法的声明吗?

Is it okay to think of the first statement as a declaration of a static method, and the second statement as a declaration of an instance method?

推荐答案

是的,第一个函数与 构造函数,你可以把它当作一个'静态方法'.

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

在 JavaScript 中,函数是 first-class 对象,这意味着您可以像对待任何对象一样对待它们,在这种情况下,您只需向函数对象添加一个属性.

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.

第二个函数,当您扩展构造函数原型时,它将可用于所有使用 new 关键字,以及该函数内的上下文(this 关键字)将引用您调用它的实际对象实例.

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.

考虑这个例子:

// 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();

这篇关于JavaScript:Class.method 与 Class.prototype.method的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆