【JS】原型和原型链的几道练习题

777 阅读1分钟

第一题

 function Fn() {
            this.x = 100;
            this.y = 200;
            this.getX = function () {
                console.log(this.x);
            }
        }
        Fn.prototype.getX = function () {
            console.log(this.x);
        };
        Fn.prototype.getY = function () {
            console.log(this.y);
        };
        let f1 = new Fn;
        let f2 = new Fn;

        console.log(f1.getX === f2.getX);
        console.log(f1.getY === f2.getY);
        console.log(f1.__proto__.getY === Fn.prototype.getY);
        console.log(f1.__proto__.getX === f2.getX);
        console.log(f1.getX === Fn.prototype.getX);
        console.log(f1.constructor);
        console.log(Fn.prototype.__proto__.constructor);
        f1.getX();
        f1.__proto__.getX();
        f2.getY();
        Fn.prototype.getY();
答案: false  true  true  false false   Fn函数  Object 100 undefined 200  undefined

第二题

function fun(){
    this.a=0;
    this.b=function(){
        alert(this.a);
    }
}
fun.prototype={
    b:function(){
        this.a=20;
        alert(this.a);
    },
    c:function(){
        this.a=30;
        alert(this.a)
    }
}
var my_fun=new fun();

my_fun.b();   
my_fun.c(); 
答案:"0"  "30"

第三题

需求:在Object的原型上,手写一个检测是否是公有属性的方法 hasPublicProperty
 Object.prototype.hasPublicProperty = function (attr) {
        if (attr in this) {
            if (this.hasOwnProperty(attr)) {
                return false
            } else {
                return true
            }
        } else {
            return false
        }
    }

第四题

需求:手写plus 和 minus 方法,实现以下运算
    let n = 10;
    let m = n.plus(10).minus(5);
    console.log(m); //=>15(10+10-5)
Number.prototype.plus = function (num) {
        return this + num
    }
Number.prototype.minus = function (num) {
        return this - num
    }

    let n = 10;
    let m = n.plus(10).minus(5);
    console.log(m); //=>15(10+10-5)

注:如果只是为了实现这个需求,这样写就可以了。如果对于运算方法的整体来考虑,当然也可以加入对于参数的判断,如果不是数字类型的,先转化为数字类型,然后进行运算,如果转化为数字类型是NaN的,可以选择报错或者返回0等,自行选择。