正在调用Javascript对象中的函数

Calling function in Javascript object

本文关键字:函数 对象 Javascript 调用      更新时间:2023-10-14

我定义了一个具有两个属性和一个名为fullname的函数的对象。当我调用函数全名时,我会看到显示的另一行。

<html>
    <head>
        <script>
            function person(firstname,lastname){
                this.firstname = firstname;
                this.lastname = lastname;
                var id = 1;
                this.fullname = function(){
                console.log("firstname = " + firstname + " lastname = " + lastname);    
                }
            }
            x = new person("Bob","McDonald");
            console.log(x.firstname);
            console.log(x.fullname());
            console.log("Display finish");
        </script>
    </head>
    <body>
        This is the body
    </body>
</html>

来自firebug的输出-

Bob
basics.html(第14行)firstname=Bob lastname=McDonald
basics.html(第9行)未定义
basics.html(第15行)显示完成

您的函数fullname已经登录到控制台,并且什么也不返回。你只需要称之为

console.log(x.firstname);
x.fullname(); //no console.log
console.log("Display finish");