关于原型和面向对象,有的时候感觉自己搞懂了,这时候,我们就需要一些题目检测检测自己是否真的搞懂了。
function Fn() {
this.x = 100
this.y = 200
this.getX = function () {
console.log(this.x)
}
}
Fn.prototype.getX = function () {
console.log(this.x)
}
Fn.prototype.getY = function () {
console.log(this.y)
}
let f1 = new Fn
let f2 = new Fn
console.log(f1.getX === f2.getX) //false
console.log(f1.getY === f2.getY) //true
console.log(f1.__proto__.getY === Fn.prototype.getY) //true
console.log(f1.__proto__.getX === f2.getX) //false
console.log(f1.getX === Fn.prototype.getX) //false
console.log(f1.constructor) //Fn
console.log(Fn.prototype.__proto__.constructor) //Object
f1.getX() //100
f1.__proto__.getX() //undefined
f2.getY() //200
Fn.prototype.getY() //undefined
function Fn() {
this.a = 0
this.b = function () {
alert(this.a)
}
}
Fn.prototype = { //重构Fn的原型对象,没有constructor属性了
b: function () {
this.a = 20
alert(this.a)
},
c: function () {
this.a = 30
alert(this.a)
}
}
var fn = new Fn
fn.b() //0
fn.c() //30
内置类的原型不允许重构。Array.prototype = {...},这样写是没有用的。增加内置类原型的方法: Array.prototype.xxx = function(){...}
function C1(name) {
if (name) {
this.name = name
}
}
function C2(name) {
this.name = name
}
function C3(name) {
this.name = name || 'join'
}
C1.prototype.name = 'Tom'
C2.prototype.name = 'Tom'
C3.prototype.name = 'Tom'
alert((new C1().name) + (new C2().name) + (new C3().name)) //Tomundefinedjoin
function Fn(num) {
this.x = this.y = num
}
Fn.prototype = {
x: 20,
sum: function () {
console.log(this.x + this.y)
}
}
let f = new Fn(10)
console.log(f.sum === Fn.prototype.sum) //true
f.sum() //20
Fn.prototype.sum() //NaN
console.log(f.constructor) //Object
function Fn() {
let a = 1
this.a = a
}
Fn.prototype.say = function () {
this.a = 2
}
Fn.prototype = new Fn
let f1 = new Fn
Fn.prototype.b = function () {
this.a = 3
}
console.log(f1.a) //1
console.log(f1.prototype) //undefined
console.log(f1.b) //function(){this.a = 3}
console.log(f1.hasOwnProperty('b')) // false
console.log('b' in f1) //true
console.log(f1.constructor === Fn) //true