实例对象使用的属性或者方法,先在实例对象中找,找到了直接使用,如果找不到,就去实例对象__proto__指向的原型对象中找,找到了直接使用,如果找不到,就报错;
1)为内置对象添加原型方法:
Array.prototype.mySort=function(){
//this 指的是 实例对象 arr
for(let i =0;i<this.length-1;i++){
for(let j =0;j<this.length-1-i;j++){
if(this[j]<this[j+1]){
var tmp = this[j];
this[j]=this[j+1];
this[j+1]=tmp;
}
}
}
}
String.prototype.sayHi=function(){
//this 是实例对象 str
console.log(this+"哈哈哈,你好");
}
var arr =[1,2,42,33,22,7,5699,89,800];
arr.mySort();
console.log(arr); //[5699, 800, 89, 42, 33, 22, 7, 2, 1]
var str="小明";
str.sayHi(); // 输出 小明哈哈哈,你好
待续。。。。。。。