都是绑定在使用构造函数创建出来的对象p上; 最终使用的时候也是使用对象p来进行访问;
function Person(name, age, doFunc) {
this.name = name;
this.age = age;
this.doFunc = doFunc;
}
var p1 = new Person('sz', 18, function () {
console.log('sz在上课');
});
var p2 = new Person('王二小', 18, function () {
console.log('王二小在放羊');
});
函数本质也是一个对象, 既然是个对象, 那么就可以动态的添加属性和方法
只要函数存在, 那么绑定在它身上的属性和方法, 也会一直存在
eg,记录总共创建了多少个人对象:
// 1. 设置一个全局的变量
var personCount = 0;
function Person(name, age, doFunc) {
this.name = name;
this.age = age;
this.doFunc = doFunc;
personCount++;
}
var p1 = new Person('sz', 18, function () {
console.log('sz在上课');
});
var p2 = new Person('王二小', 18, function () {
console.log('王二小在放羊');
});
console.log('总共创建了'+ personCount + '个人'); //2
function Person(name, age, doFunc) {
this.name = name;
this.age = age;
this.doFunc = doFunc;
if (!Person.personCount) {
Person.personCount = 0; //创建静态属性
}
Person.personCount++;
}
//创建静态方法
Person.printPersonCount = function () {
console.log('总共创建了'+ Person.personCount + '个人');
};
var p1 = new Person('sz', 18, function () {
console.log('sz在上课');
});
var p2 = new Person('王二小', 18, function () {
console.log('王二小在放羊');
});
Person.printPersonCount();
原文:https://www.cnblogs.com/tangge/p/11633063.html