Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save StuPig/2658648 to your computer and use it in GitHub Desktop.
Save StuPig/2658648 to your computer and use it in GitHub Desktop.
探究JavaScript类的属性(property)、原型继承(prototype inheritence)、和构造器(constructor)
// 先定义一个Person类
var Person = function (name, age) {
this.name = name;
this.age = age;
this.tmp = 'this.tmp';
this.sayName = function() {
console.log('this.sayName(): ', this.name);
}
}
Person.prototype.sayAge = function() {
console.log('Person.prototype.sayAge(): ', this.age);
}
Person.prototype.tmp = 'Person.prototype.tmp';
// 实例化Person类
var p = new Person('StuPig', 24);
// 看下Person的实例p都有什么
console.dir(p);
// Person
// age: 24
// name: "StuPig"
// sayName: function () {
// __proto__: Object
// constructor: function (name, age) {
// sayAge: function () {
// __proto__: Object.prototype
// 再看看Person.prototype上都有什么
console.log('Person.prototype: ', Person.prototype);
// Object
// constructor: function (name, age) {
// sayAge: function () {
// __proto__: Object.prototype
function extend(subClass, superClass) {
var F = function () {};
F.prototype = new superClass();
subClass.prototype = new F();
subClass.prototype.constructor = subClass;
subClass.superClass = superClass;
if (superClass.prototype.constructor == Object.prototype.constructor) {
superClass.prototype.constructor = superClass;
}
}
var Programmer = function (name, age, gender) {
// Programmer.superClass.constructor.call(this);
this.gender = gender;
}
extend(Programmer, Person);
Programmer.prototype.sayGender = function() {
console.log('Programmer.prototype.sayGender(): ', this.gender);
}
console.log('Programmer.prototype: ', Programmer.prototype);
var stupig = new Programmer('StuPig', 24, 'male');
// console.dir(stupig);
console.dir(stupig.__proto__);
stupig.sayGender();
stupig.sayAge();
stupig.sayName();
// 1.构造器 constructor 只是原型上的一个属性,instanceof 的判断是不依靠 constructor 的,而是依靠原型
// 因此原型上一个属性的更改,不会左右 instanceof 的判断。
var A = function () {};
A.prototype = {
a: 'a'
}
var a0 = new A();
console.log(A.prototype.constructor); // function Object() { [native code] }
console.log(a0.a); // 'a'
console.log(a0.constructor); // function Object() { [native code] }
var B = function () {this.a = 'b'};
B.prototype.a = 'c'
var a1 = new A();
a1.__proto__.constructor = B;
console.log(a1);
// A
// __proto__:
// a: 'a'
// constructor: function () {this.a = 'b'}
// prototype:
// a: 'c'
// constructor: function () {this.a = 'b'} 继续向下就是 constructor.protype 与 prototype.constructor 的循环引用
// __proto__: function Empty() {}
// __proto__: Object.prototype
console.log(a0.constructor); // function () { this.a = 'b' } 也就是是B的构造函数
console.log(a1.constructor); // 同上,因为他们都是基于同一个原型A.prototype继承过来的,改了a1的,则a0的也改了
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment