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

查看:123
本文介绍了JavaScript:Class.method vs. 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函数中 一流的 对象,这意味着您可以像对待任何对象一样对待它们在这种情况下,您只是向函数对象。

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 keyword)将引用您调用它的实际对象实例。

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 vs. Class.prototype.method的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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