JavaScript之构造函数

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(){}
原文地址:https://www.cnblogs.com/mabylove/p/7736093.html