JavaScript之構造函數
阿新 • • 發佈:2017-10-26
prototype 需要 const 屬性方法 特殊 火星 私有方法 .sh object
js中構造函數:
// 構造函數 function Dog(sex) { // 公有屬性 this.sex = sex; this.name = ‘blog‘; // 私有屬性 var sound = ‘汪汪汪‘; var that = this; // 私有方法 function showName() { console.log(that.name); } showName(); } /* * 向構造函數添加 公有屬性/公有方法 * 需要用到prototype * prototype 屬性:使你有能力向對象添加屬性和方法。 * 向prototype中添加成員將會把新方法添加到構造函數的底層中去*/ // 公有屬性 Dog.prototype.color = ‘red‘; // 公有方法 Dog.prototype.run = function() { return "10 km/h"; } /* * 向構造函數添加 靜態屬性/靜態方法 * 註意部分特殊屬性:如name默認指向方法名,修改此靜態名稱可能始終是方法名 */ // 靜態屬性 Dog.address = ‘火星‘; // 靜態方法 Dog.showSex = function (dog) { return dog.sex; } // 實例化 var dog1 = new Dog(‘boy‘);// 1.調用公有屬性/方法 console.log("color :",dog1.color) // red console.log("run :",dog1.run()) // 10 km/h // 2.調用私有屬性/方法 console.log("address :",dog1.constructor.address) // 火星 console.log("showSex :",dog1.constructor.showSex(dog1)) // boy
// 3.屬性方法查看
console.log("constructor :",dog1.prototype) // undefind console.log("prototype -Dog-:",Dog.prototype) //{object} console.log("constructor :",dog1.constructor) // function(){} console.log("constructor -Dog-:",Dog.constructor) // function(){}
JavaScript之構造函數