JS中构造函数与普通函数区别

114 阅读1分钟

1.构造函数也是一个普通函数,创建方式和普通函数一样,但构造函数命名一般首字母大写;

2.构造函数和普通函数调用方式不一样,作用也不一样,构造函数用来新建对象实例

function demo() {    // TODO...    }
function Demo() {    // TODO...    }
1.普通行数调用方式:
demo();
2.构造函数调用方式:
var test = new Demo();

3.构造函数内部勇this来构造属性和方法

function Dog(name, age, legs) {
    this.name = name;
    this.age = age;
    this.legs = legs;
    this.say = function() {
        alert("汪汪汪");
    }
}

4.构造行数的执行流程

a.在堆中创建一个新对象

b.将新对象的设置为行数中的this

c.逐行执行构造函数中的代码

d.将新建对象作为构造函数的返回值

5.普通函数除非主动return一个对象,是没有返回值的

function dog() {
    // TODO ...
}
var dogDemo = dog();
console.info(dogDemo);  // 输出undefined

6.用instanceof检查一个对象是否是一个类的实例;

function Dog(name, age, legs) {
    this.name = name;
    this.age = age;
    this.legs = legs;
    this.say = function() {
        alert("汪汪汪");
    }
}
var dogDemo = new Dog('Tom', 14, 4);
console.info(dogDemo); // Dog{ name: 'Tom', age: 14, legs: 4, say: function}
console.info(dogDemo instanceof Dog); // true
console.info(dogDemo.hasOwnProperty('age'); // true