方法 类 原型 实例 一些练习题

140 阅读1分钟
//定义一个方法
function Foo() {
    getName = function () {
        console.log(1);
    };
    return this;
}

//添加类静态方法
Foo.getName = function () {
    console.log(2);
};
//在类的原型上添加方法
Foo.prototype.getName = function () {
    console.log(3);
};
//全局方法变量提升
var getName = function () {
    console.log(4);
};
//全局声明方法,声明并赋值
function getName() {
    console.log(5);
}
Foo.getName();      //2
getName();          //4

//调用Foo方法,改变全局的getName,返回的this是window
Foo().getName();    //1
getName();          //1
new Foo.getName();      //2
new Foo().getName();    //3

new new Foo().getName();    //3

let Fn = function (x = 0, y = 0) {
    this.x = x;
    this.y = y;
    this.getX = function () {
        console.log(this.x);
    }
};
Fn.prototype.getX = function () {
    console.log(this.x);
};
let f1 = new Fn;//{x:0.y:0,getX}
Fn.prototype = {
    getY: function () {
        console.log(this.y);
    }
};
let f2 = new Fn(1, 2);  //{x:1.y:2,getX}
console.log(f1.constructor===f2.constructor); 
//true,f1和f2都是Fn的实例从原型链上找constructor都是Object
f1.getX();  //0

f1.getY();  //0

f1.__proto__.getX();    //报错
f1.__proto__.getY();    //undefined
f2.getX();                  //1
f2.getY();                  //2
f2.__proto__.getX();       //报错
f2.__proto__.getY();        //undefined

    //全局下的n:7
let n = 2,
fn = () => {
//this指向window,let声明的变量不挂载到window上
    this.n *= 3;
    n++;
    return m=>console.log((++n)+m);
};
var f = fn(4);
f(5);       //9
fn(4)(5);   //11
f(6);   //13
console.log(n); //7

//考察知识点箭头函数没有自己的this它的this是父级作用域的this这里就是window

let fn1=function(){
    alert(1)
  },
fn2=function(){alert(2)};
fn1.call(fn2);  //"1"

fn1.call.call.call(fn2);    //"2"
//相当于执行call方法,改变call的内部指向为fn2,call方法中的this指向执行的函数,第二个参数开始,是为call传入的参数,改变fn2的this指向为第二个参数,之后的参数就是fn2的参数
//总结下来就是相当于执行fn2方法,改变内部this指向为第二个参数,剩下的参数是调用fn2时传递的参数

window.val = 1;//4
let json = {
    val: 10,    //20
    dbl: function () {
        console.log(this.val)
        this.val *= 2;
    }
};
json.dbl(); //10
let dbl = json.dbl;
dbl();  //1
json.dbl.call(window);  //2
alert(window.val + json.val);  //24