JavaScript自定义构造函数

    科技2024-04-14  174

    自定义构造函数

    1、自定义构造函数约定成俗的采用大驼峰的写法,即所有单词首字母都大写 2、删除对象中的方法,切记删除方法函数不要加括号 3、同一个构造函数创建的不同对象来说,每个对象的属性和方法执行都互不干扰

    实例

    <script charset="utf-8"> function Person(person){//自定义构造函数约定成俗的采用大驼峰的写法,即所有单词首字母都大写 this.name = person.pName; this.age = person.pAge; this.weight = person.pWeight; this.eat = function(){ console.log("我是"+this.name+",我正在吃饭"); this.weight++;//this代表所在的对象 }; this.run = function () { console.log("我是"+this.name+",我正在跑步"); this.weight--;//this代表所在的对象 inrun = "abc"; }; this.swim = function (n) { console.log("我是"+this.name+",我正在游泳"); this.weight -=n;//this代表所在的对象 }; this.drink = function (n) { console.log("我是"+this.name+",我喝了第"+n+"瓶酒"); this.weight +=n;//this代表所在的对象 }; } var zhangSan = new Person({ pName: "张三", pAge: 33, pWeight: 160 }); zhangSan.run(); console.log(zhangSan.weight); var liSi = new Person({ pName: "李四", pAge: 26, pWeight: 170 }); liSi.swim(10); console.log(liSi.weight); //删除对象中的属性 delete zhangSan.age; console.log(zhangSan.age); //删除对象中的方法,切记删除方法函数不要加括号 delete zhangSan.drink; </script>
    Processed: 0.012, SQL: 9