<script type="text/javascript">
function Star(uname,age){
this.uname=uname;
this.age=age;
}
var _this;
Star.prototype.sing=function(){
console.log('唱歌');
_this=this;
console.log(this);
}
var ldh=new Star('刘德华',18)
ldh.sing();
_this.sing();
console.log(ldh);
console.log(_this === ldh)
console.log(Function.prototype);
console.log(Object.prototype);
console.log(Array.prototype);
Array.prototype.sum = function(user){
// console.log(this);
// var num = 0;
// for(var i=0;i<=user;i++){
// num+=i;
// }
// return this.push(num);
// }
// var arr = [];
// arr.sum(100);
// console.log(arr);
// Array.prototype.pushs = function(user){
// this[this.length] = user
// }
// var arr = [11,22,33];
// arr.pushs(44);
// console.log(arr);
// Array.prototype.pops = function(){
// this.length = this.length-1;
// }
// var arr = [11,22,33];
// arr.pops();
// console.log(arr);
// Array.prototype.shifts = function(){
// for(var i=0;i<this.length-1;i++){
// this[i] = this[i+1];
// }
// this.length = this.length-1;
// }
// var arr = [11,22,33];
// arr.shifts();
// console.log(arr);
// Array.prototype.unshifts = function(user){
// this.length = this.length+1;
// for(var i=this.length-1;i>=0;i--){
// this[i] = this[i-1];
// }
// this[0] = user;
// }
// var arr = [11,22,33];
// arr.unshifts(44);
// console.log(arr);
// call()方法原理
// Function.prototype.calls = function(user,...a){
// if(!user||user==null||user==undefined){
// user = window;
// }
// let fn = Symbol();
// user[fn] = this;
// return user[fn](...a);
// }
// let obj = {
// func(a,b){
// console.log(this);
// console.log(this.age);
// console.log(a);
// console.log(b);
// }
// }
// let obj1 = {
// age:"张三"
// }
// obj.func.calls(obj1,1,2);
// bind()原理
Function.prototype.myBind = function(context) {
// 如果没有传或传的值为空对象 context指向window
if (typeof context === "undefined" || context === null) {
context = window
}
let fn = mySymbol(context)
context[fn] = this //给context添加一个方法 指向this
// 处理参数 去除第一个参数this 其它传入fn函数
let arg = [...arguments].slice(1) //[...xxx]把类数组变成数组,arguments为啥不是数组自行搜索 slice返回一个新数组
context[fn](arg) //执行fn
delete context[fn] //删除方法
}
// apply原理一致 只是第二个参数是传入的数组
Function.prototype.myApply = function (context, args) {
if (!context || context === null) {
context = window;
}
// 创造唯一的key值 作为我们构造的context内部方法名
let fn = Symbol();
context[fn] = this;
// 执行函数并返回结果
return context[fn](...args);