鉴别一个原型属性
function hasPrototypeProperty(object, name) {
return name in object && !object.hasOwnProperty(name);
}
在构造函数中使用原型对象
function Person(name) {
this.name = name;
}
Person.prototype = {
constructor: Person,
sayName: function () {
console.log(this.name);
},
toString: function() {
}
};
var person1 = new Person('Nicholas');
var person2 = new Person('Greg);
console.log(person1 instanceof Person); // true
console.log(person1.constructor === Person); // true
console.log(person1.constructor === Object); // false
console.log(person2 instanceof Person); // true
console.log(person2.constructor === Person); // true
console.log(person2.constructor === Object); // false
对象继承
var person1 = {
name: 'Nicholas',
sayName: function () {
console.log(this.name);
}
};
var person2 = Object.create(person1, {
name: {
configurable: true,
enumerable: true,
value: 'Greg',
writable: true
}
});
person1.sayName(); // Nicholas
person2.sayName(); // Greg
console.log(person1.hasOwnProperty('sayName')); // true
console.log(person1.isPropertyOf(person2)); // true
console.log(person2.hasOwnProperty('sayName')); // false
模块模式
var person = (function () {
var age = 25;
function getAge() {
return age;
}
function growOlder() {
age++;
}
return {
name: 'Nicholas',
getAge: getAge,
growOlder: growOlder
};
}());
作用域的构造函数
function Person(name) {
this.name = name;
}
Person.prototype.sayName = function() {
console.log(this.name);
};
var person1 = Person('Nicholas');
console.log(person1 instanceof Person); // false
console.log(typeof person1); // undefined
console.log(name); // Nicholas
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。