创建一个类方法

时间:2016-06-22 23:33:25

标签: javascript

function Person(firstName = "John", lastName = 'Doe', age = 0, gender = 'Male') {
    this.firstName = firstName;
    this.lastName = lastName;
    this.age = age;
    this.gender = gender;
    this.sayFullName = function() {
        return this.firstName + " " + this.lastName
    };
}

Person.prototype.greetExtraTerrestrials = function(raceName) {
    return `Welcome to Planet Earth ${raceName}`;
};

这段代码有什么问题?它是否创建了一个名为greetExtraTerrestrials的类方法?

3 个答案:

答案 0 :(得分:1)

不要将该功能放在原型上,将其置于Class本身,如

Person.greetExtraTerrestrials = function(raceName) { 
    return `Welcome to Planet Earth ${raceName}`;
};

并将其称为

Person.greetExtraTerrestrials('ABC');

答案 1 :(得分:1)

您可以两者

的区别
class Person(...) {
    ...
}

Person.myFunction = function(val) { // This is a public function
    return val;
}

Person.prototype.myFunction = function(val) { // This is a private function
    return val;
}

访问的方式。

访问 public 功能:

var r = Person.myFunction("Hello!");
console.log(r);

访问私人功能:

var person1 = new Person(...);
var r = person1.myFunction("Hello!");
console.log(r);

另见question

答案 2 :(得分:0)

实际上它可行,但首先你需要创建一个Person实例才能调用它的方法。例如:

var john = new Person("John");
console.log(john.greetExtraTerrestrials("predator"));