为什么这个函数不能在面向对象的javascript风格中工作?

Aar*_*ron 2 javascript

我试图访问该函数作为person对象的方法为什么它不会访问该方法并执行该函数应该做的事情?

function Person(name, age, location) {
this.name= name;
this.age = age;
this.location = location;
this.test = function() {
    alert("TEST");
};

}   
var Matt = new Person("Matthew", "21", "South Africa");
Matt.test;
Run Code Online (Sandbox Code Playgroud)

McS*_*tch 8

您需要使用括号调用该方法:

Matt.test();
Run Code Online (Sandbox Code Playgroud)

这将执行该功能.否则你得到的Matt.test就是函数本身,可以传递给另一个函数,存储在变量中等等.然后你可以在以后执行这个函数.