1. 程式人生 > >js建立物件 三 自定義構建函式建立物件

js建立物件 三 自定義構建函式建立物件

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>$永遠的24k純帥$</title>
  <script>

    //自定義建構函式建立物件,我要自己定義一個建構函式,自定義建構函式,建立物件
    //函式和建構函式的區別;名字是不是大寫(首字母是大寫)
    function Person(name,age) {
      this.name=name;
      this.age=age;
      this.sayHi=function () {
        console.log("我叫:"+this.name+",年齡是:"+this.age);
      };
    }

    //自定義建構函式建立物件:先自定義一個建構函式,建立物件
    var obj=new Person("小明",10);
    console.log(obj.name);
    console.log(obj.age);
    obj.sayHi();

    var obj2=new Person("小紅",20);
    console.log(obj2.name);
    console.log(obj2.age);
    obj2.sayHi();


    console.log(obj instanceof Person);
    console.log(obj2 instanceof  Person);


    //自定義狗的建構函式,建立物件
    function Dog(name,age,sex) {
      this.name=name;
      this.age=age;
      this.sex=sex;
    }
    var dog=new Dog("大黃",20,"男");
    console.log(dog instanceof Person);//false
    console.log(dog instanceof Dog);

 

 


  </script>
</head>
<body>


</body>
</html>