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

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

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


#1楼

是的,第一个函数与该构造函数的对象实例无关,您可以将其视为“静态方法”

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

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

考虑以下示例:

// constructor function
function MyClass () {var privateVariable; // private member only available within the constructor fnthis.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 instancemyObj.publicMethod();
MyClass.staticMethod();

#2楼

当创建多个MyClass实例时,内存中仍然仍然只有一个publicMethod实例,但是如果使用privateMethod,则最终将创建许多实例,而staticMethod与对象实例没有任何关系。

这就是为什么原型可以节省内存。

另外,如果您更改父对象的属性,并且未更改子对象的相应属性,则会对其进行更新。


#3楼

对于视觉学习者,在定义不带.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 consoleJS Bin生成的结果
单击上面的jsbin链接以逐步执行代码。
使用ctrl切换注释的部分+ /


#4楼

是的,第一个是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是静态方法,而sayHiPerson的实例方法。

下面是如何从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仍然是一种无类语言。 ES6中引入的class主要是在现有的基于原型的继承模型上的语法糖。

JavaScript:Class.method与Class.prototype.method相关推荐

  1. Do not access Object.prototype method ‘hasOwnProperty‘ from target object

    Do not access Object.prototype method 'hasOwnProperty' from target object 编写代码的时候,使用了eslint: let obj ...

  2. IDEA中@override注解报错信息“Method does not override method from its superclass“

    IDEA中@override注解报错信息"Method does not override method from its superclass" 出现问题原因: 1. 首先查看这 ...

  3. Android Studio Method does not override method from its superclass

    Android Studio 出现 Method does not override method from its superclass 解决方式如下 在可编辑代码处右键点击 Generate -- ...

  4. JavaScript中为何要使用prototype

    在JavaScript学习和工作中,或多或少会接触一些底层的JavaScript知识.比如下面四个基本概念: 1.prototype 2.this关键字 3.原型继承 4.JavaScript闭包 个 ...

  5. JavaScript——this、constructor、prototype

    this this表示当前对象,如果在全局作用范围内使用this,则指代当前页面对象window: 如果在函数中使用this,则this指代什么是根据运行时此函数在什么对象上被调用. 我们还可以使用a ...

  6. JAVA反射系列之Method,java.lang.reflect.Method的使用

    摘要: ava.lang.reflect.Method的基本使用. 最近写项目,用反射的比较多,写一个总结,以便查阅. Method是反射最基本的一个类. 直接上代码: [java] view pla ...

  7. JavaScript 之call , apply 和prototype 介绍

    1. 前言 为什么将这三个概念放在一起说.原因是这些是会在实现js 继承会需要使用到的 2. call 和 apply call 和 apply 的作用基本类似, 都是去执行function并将这个f ...

  8. JAVA反射系列之Method,java.lang.reflect.Method的使用。

    2019独角兽企业重金招聘Python工程师标准>>> 最近写项目,用反射的比较多,写一个总结,以便查阅. Method是反射最基本的一个类. 直接上代码: /*** @ClassN ...

  9. javascript对象的property和prototype是这样一种关系

    ECMAScript可以识别两种类型的对象,一种叫做Native Object属于语言范畴;一种叫做Host Object,由运行环境提供例如document对象, Dom Node等 Native ...

最新文章

  1. edgesForExtendedLayout、automaticallyAdjustsScrollV
  2. 来场产品设计师的对决吧!MacBook、大疆OSMO等你拿
  3. Java集合框架:HashMap
  4. 为JavaOne 2014做好准备!
  5. 2021双11上云狂欢节 | 爆款产品底价全面开售
  6. 开源+技术影响力,联创共建云端技术生态|TeaTalk·Online演讲实录
  7. 如何在Go中找到一个对象的类型?
  8. C语言三个链表的关联,有能者相互切磋---怎样实现ABC三个链表的相互操作?
  9. 多易大数据学习实况记录
  10. 后flash时代的何去何从
  11. python 输出sql汉字_emai中的pythonsql输出
  12. 怎么创建账户Crowd 和 JIRA、Confluence、Fisheye and Crucible、GitLab共享账户已经集成登入
  13. Deel:20个月,ARR 1M to 100M。
  14. GD32F4(2): 用keil5打开官方评估版demo,编译报错找不到core_cm4.h文件
  15. ES2015中let的暂时性死区(TDZ)
  16. 《响应式Web设计实践》一2.1 布局选项
  17. 后羿采集器怎么导出数据_数据采集教程_智能模式_如何设置自动导出_后羿采集器...
  18. 华为AC忘记console密码
  19. 全球与中国便携式USB摄像机市场现状及未来发展趋势(2022)
  20. 基于三维GIS技术的公路交通数字孪生系统

热门文章

  1. ListView Viewholder的坑 线性布局的坑
  2. python gpu加速库比matlab快吗_为什么异步库比此I/O绑定操作的线程慢?
  3. python渐变颜色表_python – 具有固定颜色渐变的np.histogram2D
  4. Java学习笔记21
  5. ubuntu16.04安装retext,第一行图标flie,edit,help没有,其它图标也不显示?
  6. RxSwift ViewModel定义
  7. iOS架构-cocoapods之本地git库的管理(15)
  8. python增删改查的框架_python的Web框架,Django的ORM,模型基础,MySQL连接配置及增删改查...
  9. Docker大行其道—镜像
  10. 再谈移动端Web屏幕适配