JavaScript基础-构造函数及实例化

53 阅读1分钟

1. 构造函数

构造函数与普通函数大致一样,都是通过function关键字进行声明,不同的是,通过new关键字获取构造函数实例,通常构造函数遵循大驼峰命名。构造函数更接近与面向对象编程。

function 函数名称(形参列表) {
    函数体
}

function Dog() {
    this.doing = function () {
        console.log('在跑步')
    }
}

var dog = new Dog();
dog.doing(); // 在跑步

1.1. 构造函数this指向

  • 通常情况下,构造函数中的this指向new实例出来的实例对象。
function Test() {
    this.getInstance = function (){
        return this;
    }
}

var test = new Test();
var instance = test.getInstance();
console.log(test === instance); // true
  • 每次new出来的实例相互独立,互不干扰。
function Dog(name) {
    this.name = name;
    
    this.getName = function () {
        console.log(this.name)
    }
}

var dog1 = new Dog('花花');
var dog2 = new Dog('冬冬');
var dog3 = new Dog('花花');
console.log(dog1.getName(), dog2.getName());// 花花   冬冬
console.log(dog1 == dog2); // false
  • 当构造函数里返回的是一个原始值,则构造函数的this指向实例,当构造函数返回一个对象,则实例等于返回的对象
function Test1() {
  this.do = function () {
    console.log('do...');
  };
  return {};
}

function Test2() {
  this.do = function () {
    console.log('do...');
  };
  return '2';
}

var test1 = new Test1();
test1.do();
console.log(test1); // TypeError: test.do is not a function

var test2 = new Test2();
test2.do();
console.log(test2); // do...