通过类名点原型点方法名称调用 java 脚本类方法

Calling a java script class method by class name dot prototype dot method name

本文关键字:调用 java 类方法 脚本 原型 方法      更新时间:2023-09-26

我需要理解以下代码。有人可以解释一下吗?

var MyClass = function(){
 this.publicMethod = function(){
  console.log("I am a public method");
 }
 MyClass.prototype.foo = function(){ //Need to know how it is working.
  console.log('I am in foo');
 }
}
var myClassObject = new MyClass();
MyClass.prototype.foo(); // If I don't include the above line it throws an exception.

我需要知道最后两个语句是如何工作的?

这个问题实际上与类或原型无关。

如果不调用 var myClassObject = new MyClass(); ,则永远不会执行MyClass,并且永远不会发生分配MyClass.prototype.foo = function(){}

下面是一个更简单的示例:

var foo;
function bar() {
    foo = 42;
}
console.log(foo);

foo将被undefined,因为从不调用bar,也无法更改foo的值。

通常,在构造函数本身之外定义构造函数的原型。没有理由在构造函数中执行此操作,因为它会不断(并且不必要地)重新定义自己。请考虑以下模式:

//data specific to the instance goes into the constructor
var Employee = function (first, last) {
   this.firstName = first;
   this.lastName = last;
}
//prototype methods defined outside constructor. Only defined once
//getFullName method will be available on any instance of an Employee called by
//'new Employee(...)'
Employee.prototype.getFullName = function () {
   return this.firstName + " " + this.lastName;
}
var alice = new Employee("Alice", "Smith");
var bob = new Employee("Bob", "Doe");
console.log(alice.getFullName());
console.log(bob.getFullName());

我需要知道最后两个语句是如何工作的?

这很容易,coz prototype可以在已经创建的对象中添加函数或在 js 中添加"类"。但这是软错别字。如果没有特定功能,原型将被触发。

检查这个:http://plnkr.co/edit/hu5UYKduodhUZt2GH1N5?p=preview

现在检查一下:http://plnkr.co/edit/Gt8v2il0Exx6g715Ir1d?p=preview

你看到不同的了吗?

在第二个示例中,原型不起作用,因为MyClass有自己的"方法"调用MakeAWishSecond但在第一个示例中,MyClass 没有自己的MakeAWishSecond"方法"。

如果您使用原型,则可以向所有对象/"类"添加一些"方法",即使在核心;)的构建中

也是如此