通过类名点原型点方法名称调用javascript类方法

时间:2014-12-22 17:25:34

标签: javascript

我需要了解以下代码。有人可以解释一下。

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.

我需要知道最后两个陈述是如何起作用的?

3 个答案:

答案 0 :(得分:1)

这个问题与课程或原型没有任何关系。

如果您不致电var myClassObject = new MyClass();,则永远不会执行MyClass,并且永远不会执行作业MyClass.prototype.foo = function(){}

这是一个更简单的例子:

var foo;

function bar() {
    foo = 42;
}

console.log(foo);

foo将为undefined,因为永远不会调用bar,也无法更改foo的值。

答案 1 :(得分:0)

通常,您在构造函数本身之外定义构造函数的原型。在构造函数中没有理由这样做,因为它会不断(并且不必要地)重新定义自己。考虑这种模式:

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

答案 2 :(得分:0)

  

我需要知道最后两个陈述是如何起作用的?

很简单,因为prototype可以在已创建的对象中添加函数,或者在js中添加“class”。 但这是一个软错字。如果没有特定功能,原型将会触发。

检查一下: http://plnkr.co/edit/hu5UYKduodhUZt2GH1N5?p=preview

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

你看到了不同的吗?

在第二个例子中,原型没有用,因为我的自己的“方法”调用MakeAWishSecond 但在第一个例子中,MyClass没有他们拥有MakeAWishSecond“方法”。

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

相关问题