乐都网站建设哪家好,网站建设 网页,犀牛云网站建设特点,网站搭建空间new是什么#xff1f;
new 运算符创建一个用户定义的对象类型的实例或具有构造函数的内置对象的实例。
function Person (name,age) {this.name namethis.age age
}
Person.prototype.sayName function () {console.log(this.name)
}
let man new Person(xl,20)
consol…new是什么
new 运算符创建一个用户定义的对象类型的实例或具有构造函数的内置对象的实例。
function Person (name,age) {this.name namethis.age age
}
Person.prototype.sayName function () {console.log(this.name)
}
let man new Person(xl,20)
console.log(man) // Person { name: xl, age: 20 }
man.sayName() // xlnew出来的实例可以访问到构造函数中的属性new出来的实例可以访问到构造函数原型链上的方法和属性
如果在构造函数内加上返回值是什么结果呢 返回基本数据类型 function Car (price) {this.price pricereturn 20
}
let bigCar new Car(90)
console.log(bigCar.price) // 90返回基本数据类型时返回值会被忽略 返回引用数据类型 function Car (price) {this.price pricereturn { km: 200 }
}
let bigCar new Car(90)
console.log(bigCar.price, bigCar.km) // undefined, 200返回引用数据类型会被正常使用
new做了什么工作呢
新建一个对象obj把obj的和构造函数通过原型链连接起来将构造函数的this指向obj如果该函数没有返回对象则返回this // new操作符做了什么function newFun(Fun, ...args) {// 1.先创建一个空对象let newObj {};// 2. 把空对象的原型指向构造函数的原型对象newObj.__proto__ Fun.prototype;// 3. 把构造函数的this绑定到新的空对象身上const result Fun.apply(newObj, args);console.log(result是, result);// 4. 根据构造函数返回的类型判断如果是值类型则忽略返回值直接返回对象如果是引用类型则返回这个引用类型console.log(返回的是引用类型吗, result instanceof Object);return result instanceof Object ? result : newObj;}function Person(name) {this.name name;// 1. 如果构造函数没有返回值则在new的时候result是undefined就会直接返回对象// 2. 如果构造函数的返回值是值类型在new的时候会忽略该返回值// return 111;// return 返回值类型--字符串;// return true;// 3. 如果构造函数的返回值是引用类型在new的时候会返回该引用类型// return { aaa: aaa };}Person.prototype.say function () {console.log(hello);};const p1 newFun(Person, 张三);p1.say();console.log(p1)