900字范文,内容丰富有趣,生活中的好帮手!
900字范文 > JS--构造函数和实例化对象

JS--构造函数和实例化对象

时间:2023-12-08 03:33:33

相关推荐

JS--构造函数和实例化对象

构造函数

在对象的创建过程中,我们发现Object就是构造函数;

new关键字调用构造函数就会得到一个对象。

var a=new Object('361546');console.log(typeof a);//'object'

new关键字做了什么?

function Stu(name,age,height){// var this={};创建新对象this.name=name;this.age=age;this.height=height;this.intr=function(){console.log(this);//this指向这个新创建的对象console.log(`${this.name}同学${this.age}岁,身高${this.height}`);}// return this;隐式返回新对象 }var obj=new Stu('乌龟',900,'20cm');obj.intr(); console.log(obj.__proto__===Stu.prototype);//新对象的隐式原型指向其构造函数

new 关键字实例化一个对象的过程:

创建一个空对象,this指向这个空对象;将新对象的隐式原型(obj.proto)指向构造函数的原型对象(Stu.prototype);执行构造函数(为新对象增添属性);隐式返回这个新对象。

案例- -无论是否用new关键字调用构造函数,都可以得到一个新对象:

构造函数也是一个函数,可以当做普通函数来执行。new.target:用于判断构造函数是否使用new关键字调用。

function Stu(name,age,height){// 判断构造函数是否通过new关键字调用--true:是if(new.target===Stu){// var this={};创建新对象this.name=name;this.age=age;this.height=height;this.intr=function(){console.log(this);//this指向这个新创建的对象console.log(`${this.name}同学${this.age}岁,身高${this.height}`);}// return this;隐式返回新对象}else{// 判断构造函数是否通过new关键字调用--false:否(手动创建新对象,写入属性(方法))var obj={name:name,age:age,height:height,intr:function(){console.log(this);//this指向手动创建的新对象console.log(`${this.name}同学${this.age}岁,身高${this.height}`); }}// 字面量创建的对象的obj.__proto__指向Object.prototypeconsole.log(obj.__proto__===Object.prototype);//--true// 手动更改obj.__proto__=Stu.prototype;// 返回该对象return obj;}}// new 调用构造函数var obj=new Stu('海龟',900,'28cm');obj.intr();console.log(obj.__proto__===Stu.prototype);//--true// 非new调用var obj2=Stu('乌龟',800,'22cm');obj2.intr();console.log(obj2.__proto__===Stu.prototype);//--true

如果函数不是通过new关键字调用,我们要手动做一些new关键字做的事:

手动创建对象–写入对象属性–this指向该对象–将新对象的obj.__proto__指向Object.prototype–返回创建的新对象

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。