这是我参与「第四届青训营 」笔记创作活动的第26天
一、构造函数和原型对象
1、构造函数原型对象prototype
prototype 属性用来向对象添加属性和方法,并且Prototype 是全局属性,适用于所有的 Javascript 对象。
function Star(uname,age){
this.uname=uname;
this.age=age;
// this.sing=function (){ //普通方法为构造函数添加函数
// console.log('..');
// }
}
Star.prototype.sing=function (){ //使用原型对象实现共享
console.log(',,,');
}
var ldh=new Star('ldh',18);
//一般情况下,我们的公共属性定义到构造函数里,公共的方法我们放到原型对象身上
2、对象原型
对象身上系统给添加了一个[[prototype]]属性,指向我们构造函数的原型对象prototype。
方法的查找规则:首先看ldh对象身上是否有sing方法,如果有就执行这个对象上的sing, 如果没有sing这个方法,因为有[[prototype]]的存在,就去构造函数原型对象prototype身上去查找sing这个方法
function Star(uname,age){
this.uname=uname;
this.age=age;
}
Star.prototype.sing=function (){
console.log('唱歌');
}
var ldh=new Star('ldh',18);
console.log(ldh);
3、原型constructor属性构造函数
在 JavaScript 中, constructor 属性返回对象的构造函数。
function Star(uname, age) {
this.uname = uname;
this.age = age;
}
//很多情况下我们需要手动 的利用constructor 这个属性来指回 原来的构造函数
Star.prototype = {
//如果我们修改了原来的原型对象,给原型对象赋值的是一个对象,则必须手动的调用constructor指回原来的构造函数
constructor: Star,
sing: function () {
console.log('.');
},
movie: function () {
console.log('..');
}
}
var ldh = new Star('ldh', 18);
console.log(Star.prototype.constructor);
console.log(ldh.constructor);
4、利用原型对象扩展内置对象方法
//原型对象的应用 扩展内置对象方法
Array.prototype.sum=function (){
//给Array对象添加一个加法运算方法
var sum=0;
for(var i=0;i<this.length;i++){
sum+=this[i];
}
return sum;
}
var arr=[1,2,3,4];
console.log(arr.sum()); //只要是利用Array创造的数组对象都可以调用这个方法