对象函数原型中名称的区别是什么?

What is the difference in names in an object function prototype?

本文关键字:区别 是什么 函数 原型 对象      更新时间:2023-09-26

如果我在JavaScript中创建一个对象,然后用prototype关键字添加一个函数,为什么这两个名称不能不同?

我有一个函数叫getName,另一个叫whatName。我不能调用whatName而没有错误。命名函数和匿名函数有什么区别?

哪一种方法更受欢迎?

代码:

Person.prototype.getName = function whatName() {
    return this.name;
};
代码:

<script>
var Person = function Person(n,f,m,l) {
    this.name = n;
    this.lname = l;
    this.fname = f;
    this.mname = m;
    this.callMeth1 = function jjj() {
    }
    this.callMeth2 = function () {
    }
    this.callMeth3 = function () {
    }
};
Person.prototype.getName = function () {
    return this.name;
};
var test = new Person("Doug");
Person.prototype.sayMyName = function() {
    alert('Hello, my name is ' + this.getName());
};
test.sayMyName();
</script>
代码:

function callMyMeth4 (a,b) {
    var aaa = a;
    var bbb = b;
}
var Person = function Person(n,f,m,l) {
    this.name  = n;
    this.lname = l;
    this.fname = f;
    this.mname = m;
    this.callMeth1 = function () {
    }
    this.callMeth2 = function () {
    }
    this.callMeth3 = function () {
    }
    this.callMeth3 = callMyMeth4(a,b); 
};

你可以这样做:

Person.prototype.getName = function () {
    return this.name;
};

如果你想使用一个已经存在的函数,那么你可以这样做:

Person.prototype.getName = whatName;

whatName是前面声明的函数的名称