构造函数与普通函数的比较

xiaoxiao2021-02-28  87

构造函数与普通函数的比较

在js中,用new关键字来调用定义的构造函数。默认返回的是一个新的对象具有构造函数定义的变量和方法。 先来写个构造函数的例子:   function Prince(name,age){ this.gender="male"; this.kind=true; this.rich=true; this.name=name; this.age=age; } Prince.prototype.toFrog=function(){ console.log("Prince "+this.name+" turned into a frog."); } var prince=new Prince("charming",25); prince.toFrog();//Prince charming turned into a frog. prince.kind;//true

 

构造函数与普通函数的区别就是: 1、用new关键字调用 var prince = new Prince(“charming”,25); 2、函数内部可以使用this关键字(普通函数原则上不可以!因为普通函数的this相当于window) 在构造函数内部,this指向的是构造出的新对象。用this定义的变量货函数/方法,就是实例变量/实例函数/方法。需要用实例才能访问到,不能用类型名访问。 prince.age;//25 Prince.age;//undefined 3、默认不用return返回值 构造函数是不需要用return显示返回值,默认会返回this,也就是新的实例对象。当然,也可以用return语句,返回值会根据return值的类型而有所不同。 4、函数命名建议首个字母大写,与普通函数区分开。 不是命名规范,但是建议这么写。     附上一个普通函数: function common(){ return("爱因斯然"); } common(); //自行脑补构造函数和普通函数的区别
转载请注明原文地址: https://www.6miu.com/read-73520.html

最新回复(0)