使用 new 调用函数

构造函数示例

function Person(name, age) {
    // this 指向新创建的对象
    this.name = name;
    this.age = age;
    
    this.introduce = function() {
        return `大家好,我是${this.name},今年${this.age}岁。`;
    };
    
    // 注意以下不同返回值的区别
    // return undefined; // 默认
    // return 123;       // 基本类型,忽略
    // return { name: '特殊对象' }; // 返回该对象
}

结果:

等待执行...

核心特点

  • 创建新的对象实例
  • this 指向新对象
  • 建立与原型(prototype)的连接
  • 如果没有返回对象,则自动返回新对象
普通函数调用

普通函数示例

function createPerson(name, age) {
    // 非严格模式下,this 指向全局对象(如 window)
    // 严格模式下,this 为 undefined
    this.name = name; // 危险,可能污染全局!
    this.age = age;
    
    return {
        name: name,
        age: age,
        introduce: function() {
            return `大家好,我是${this.name},今年${this.age}岁。`;
        }
    };
    
    // 也可以返回其他值:
    // return undefined; // 默认
    // return 123;       // 返回数字
    // return '字符串';  // 返回字符串
}

结果:

等待执行...

核心特点

  • 不创建新对象
  • this 指向全局对象(非严格模式)或 undefined(严格模式)
  • 没有与构造函数原型的连接
  • 直接返回函数体内的返回值