JS
function Person(name, age, job) {
this.name = name;
this.age = age;
this.job = job;
}
var person = new Person("Nicholas", 34, 'software Engineer');
/*
在没有使用new运算符来调用构造函数的情况下。由于该this对象是在运行时绑定的,因此直接调用Person()会将该对象绑定到全局对象window上,这将导致错误属性意外增加到全局作用域上。这是由于this的晚绑定造成的,在这里this被解析成了window对象。
解决这个问题的方案是创建一个作用域安全的构造函数。首先确认this对象是否为正确的类型实例,如果不是,则创建新的实例并返回。
*/
function Person(name, age, job) {
//检测this对象是否是Person的实例
if(this instanceof Person) {
this.name = name;
this.age = age;
this.job = job;
} else {
return new Person(name, age, job);
}
}
function Polygon(sides) {
if(this instanceof Polygon) {
this.sides = sides;
this.getArea = function() {
return 0;
}
} else {
return new Polygon(sides);
}
}
function Rectangle(width, height) {
Polygon.call(this, 2);
this.width = width;
this.height = height;
this.getArea = function() {
return this.width * this.height;
};
}
var rect = new Rectangle(5, 10);
alert(rect.sides);//undefined
function Polygon(sides) {
if(this instanceof Polygon) {
this.sides = sides;
this.getArea = function() {
return 0;
}
} else {
return new Polygon(sides);
}
}
function Rectangle(width, height) {
Polygon.call(this, 2);
this.width = width;
this.height = height;
this.getArea = function() {
return this.width * this.height;
};
}
//使用原型链
Rectangle.prototype = new Polygon();
var rect = new Rectangle(5, 10);
alert(rect.sides); //2