js精要之构造函数

// 枚举对象

  var obj = {}
    obj.name = "bob";
    obj.age = "22";
    obj.sex = "boy";
    console.log(obj);
    for(var sum in obj){
       // console.log(sum);
    }

// 构造函数 sayName自有方法

   function Person(name){
        this.name = name;
        this.sayName = function(){
            console.log(this.name);
        }
    }
    var person1 = new Person("aaa");
    var person2 = new Person("bbb");
    console.log(person1.name); // aaa
    console.log(person2.name); // bbb
    person1.sayName(); // aaa
    person2.sayName(); // bbb

// 每个函数都带有一个prototype属性  sayName1 为原型方法

  function Person1(name){
        this.name = name;
    }
    Person1.prototype.sayName1 = function(){
        console.log(this.name);
    }
    var person1a = new Person1("aaa-v");
    var person2a = new Person1("bbb-v");
    console.log(person1a.name); // aaa-v
    console.log(person2a.name); // bbb-v
    person1a.sayName1(); // aaa-v
    person2a.sayName1(); // bbb-v

// 鉴别一个原型属性

   function hasPrototypeProperty(name,object){
        return name in object && !object.hasOwnProperty(name);
    }
    var book = {
        title:"this is book!"
    }
    console.log(hasPrototypeProperty("title",book)); //false
    console.log(hasPrototypeProperty("hasOwnProperty",book)); //true

 

你可能感兴趣的:(js精要之构造函数)