构造函数常用的方法

  1. inStanceof ()
    判断 对象 是否属于 构造函数这个类
	// 构造函数Student
    function Student() {
        this.name = "王一";
    }
    // 构造函数Animal
    function Animal() {
        this.name = "汤姆";
    }
    // 对象s1
    var s1 = new Student();
    console.log(s1 instanceof Student); //true 判断s1是否属于Student类
    console.log(s1 instanceof Animal); //false 判断s1是否属于Animal类
  1. isPrototypeOf() 在原型上判断
    判断当前这个 对象 是否基于 对应原型 创建出来
	// 构造函数Student
    function Student() {
        this.name = "王一";
    }
    // 构造函数Animal
    function Animal() {
        this.name = "汤姆";
    }
    // 对象s1
    var s1 = new Student();
    console.log(Student.prototype.isPrototypeOf(s1)); //true 判断s1对象是否基于Stundent原型创建出来的
    console.log(Animal.prototype.isPrototypeOf(s1)); //false 判断s1对象是否基于Animal原型创建出来的
  1. hasOwnProperty()
    判断 对应属性 是否在 构造函数中
	// 构造函数Student
    function Student() {
        this.name = "王一";
    }
    // prototype原型
    Student.prototype.show = function () {
        console.log(this.name + "正在吃");
    }
    // 对象s1
    var s1 = new Student();
    console.log(s1.hasOwnProperty("name")); //true 判断对象s1的 name属性 是否在构造函数Student中
    console.log(s1.hasOwnProperty("show")); //false 判断对象s1的 show属性 是否在构造函数Student中
  1. 属性 in 对象
    这个 属性 是否属于 对象
	// 构造函数Student
    function Student() {
        this.name = "王一";
    }
    // prototype原型
    Student.prototype.show = function () {
        console.log(this.name + "正在吃");
    }
    // 对象s1
    var s1 = new Student();
    console.log("name" in s1); //true name属性是否属于s1对象
    console.log("show" in s1); //true show属性是否属于s1对象

面试题:写一个程序来判断某一个属性,是否是原型中得到的,对象具有这个属性,但是 这个属性还不在构造函数里

	// 构造函数Student
    function Student() {
        this.name = "王一";
    }
    // prototype原型
    Student.prototype.show = function () {
        console.log(this.name + "正在吃");
    }
    // 对象s1
    var s1 = new Student();

    function hasPrototype(key, obj) {
        // 属性在对象中,并且,对象对应属性 不在 构造函数中
        return key in obj && obj.hasOwnProperty(key) == false;
    }
    var r1 = hasPrototype("show", s1); //判断show属性 是否在s1对象的 原型中
    var r2 = hasPrototype("name", s1); //判断name属性 是否在s1对象的 原型中
    console.log(r1); //true
    console.log(r2); //false

版权声明:本文为qq_58590962原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。