實例對象使用的屬性或者方法,先在實例對象中找,找到了直接使用,如果找不到,就去實例對象__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(); // 輸出 小明哈哈哈,你好
待續。。。。。。。