怎样理解构造函数

不使用new关键字时, 构造函数是一个普通函数

function Person(name){
    var name = name;
    var sayHello = function(){
        console.log("Hello, I'm "+name);
    }
    sayHello();
}

Person(); // "success."

// 调用Array的静态方法
Array.isArray([1,2,3]); // True

 

 

使用new关键字时, 构造函数生成的是一个实例对象

function Person(name){
    this.name = name;
    this.sayHello = function(){
        console.log("Hello, I'm "+name);
    };
}

var Hanmeimei = new Person("Hanmeimei");
Hanmeimei.sayHello(); // "Hello, I'm Hanmeimei";

 

注意: 构造函数有两大特征区别于一般函数: 

1. 内部声明的变量, 如果需要被实例对象所继承, 则需要使用this关键字.

2. 只有使用new命令才会实例化一个对象, 不使用的话就跟普通函数没有区别.

posted on 2019-10-11 10:05  aisowe  阅读(596)  评论(0编辑  收藏  举报

导航