欢迎您访问 最编程 本站为您分享编程语言代码,编程技术文章!
您现在的位置是: 首页

JavaScript 构造函数的执行原则 js 中的构造函数

最编程 2024-07-17 18:55:32
...


一个构造函数,可以生成多个对象,每个对象都有相同的结构。对于JS中的任何一个普通函数,当用new关键字来调用时,它就是构造函数。

ECMAScript提供了多个内置构造函数,如 Object、Array、String、Boolean、Number、Date…等等。
var obj = new Object();
var arr = new Array();
ECMAScript也允许自定义构造函数

构造函数一般首字母会大写,为了和普通函数区分
一个构造函数可以通过new创建多个实例对象
创建构造函数时,里面的属性和方法前必须加this,this就表示当前运行时的对象

例:

function Person(name, height) {
          this.name = name;
          this.height = height;
          this.bark = function(fs){
          return fs
         
      }
     }
  
      var boy = new Person('Keith', 180);
      console.log(boy);  //Person {name: 'Keith', height: 180, bark: ƒ}
      console.log(boy.constructor);  //f Person(){}  //整个构造函数原型
      console.log(boy.bark(8));  //8
      console.log(boy.name); //'Keith'
      console.log(boy.height); //180
function Cat1(name){           
 this.name = name;
 console.log(this)  //先打印 new的时候打印  Cat1 {name: 'kk'}  
     }
 var cat3 = new Cat1("kk");
 console.log(cat3);   //后打印  Cat1 {name: 'kk'} 指向原型链,再赋值

  构造函数不需要return 就可以返回结果 :

function Dog(){
      this.name = "贝贝";
      this.bark = function(){
          console.log("汪汪汪");
      }
      // return 0;
      // return [];
  }
  var d1 = new Dog();
  console.log(d1);//Dog {name: '贝贝', bark: ƒ}
  //构造函数不需要return 就可以返回结果

构造函数原理:

1 自从用new调用函数后,JS引擎就会在内存中创建一个空对象{}
const newObj = {};
2 新对象的__proto__属性指向构造函数的原型对象
(通俗理解就是新对象隐式原型__proto__链接到构造函数显式原型prototype上。)

      newObj.__proto__ = functionName.prototype

3 构造函数内部的this会指向这个新对象(即将构造函数的作用域指向新对象)
this = newObj
4 从上到下执行函数体(只有这步是我们能直观看到代码的)
5 返回创造出来的对象(如果构造函数没有返回对象,则默认返回this。在函数体内部的this指向新创建的内存空间,默认返回 this 就相当于默认返回了该内存空间)

function Person(name, age) {
	this.name = name;
	this.age = age;
	this.eating = function() {
		console.log(this.name + ' is eating');
	}
}

const p1 = new Person('zs', 12);

//----------------------------------------------------------------------------
/*实际JS引擎帮助我们实现的操作*/
const newObj = {};
newObj.__proto__ = Person.prototype;
this = newObj;

this.name = name;
this.age = age;
this.eating = function() {
  console.log(this.name + ' is eating');
}

return newObj;

与普通函数的区别:

1 构造函数也是一个普通函数,创建方式和普通函数一样,但构造函数习惯上首字母大写

2 调用方式不一样,作用也不一样(构造函数用来新建实例对象)

   普通函数的调用方式:直接调用 person();

   构造函数的调用方式:需要使用new关键字来调用 new Person();

3 构造函数的内部用this 来构造属性和方法  

4 普通函数:因为没有返回值,所以为undefined,构造函数:马上创建一个新对象,并将该新对象作为返回值返回


上一篇: js 对象操作(对象)

下一篇: 原型

推荐阅读