Skip to content

Instantly share code, notes, and snippets.

@karenpeng
Last active August 29, 2015 14:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save karenpeng/0020d2681cea22969805 to your computer and use it in GitHub Desktop.
Save karenpeng/0020d2681cea22969805 to your computer and use it in GitHub Desktop.
function Robot(){
this.inside = []
this.a = 0
}
Robot.prototype.outside = []
Robot.prototype.b = 0
Robot.prototype.test = function(){
console.log(this.b)
}
function r2d3(){
Robot.call(this);
this.fly = true;
}
r2d3.prototype = Object.create(Robot.prototype)
r2d3.prototype.ok = function(){
console.log('ok')
}
r2d3.prototype.array = [];
// r2d3.prototype.constructor = r2d3
var robot1 = new Robot()
var robot2 = new Robot()
var robot3 = new r2d3()
var robot4 = new r2d3()
robot3.ok = function () {
console.log('not ok');
}
robot3.ok();
robot4.ok();
robot3.array.push(1);
robot3.array = [1,2,3];//why doesn't this work?
// robot3.array === [1,2,3]
// robot3.__proto__.array = [1]
console.log(robot3.array);
console.log(robot3.__proto__.array);
console.log(robot4.array === robot3.__proto__.array); // robot3 和 robot4 的 __proto__ 是同一个 === r2d3.prototype
// robot4.array 会先找 `robot4.array`, 找不到的时候去找 `robot4.__proto__.array`
//现在robot3即有.array又有.__proto__.array
//但是找到了[1,2,3]就直接用了?
// 所以最好不要在 prototype 上放非 function 的东西,误用很麻烦
// robot1.inside.push(1)
// robot1.outside.push(1)
// robot1.a = 1
// robot1.b = 2
// robot1.test = function(){
// console.log(this.outside)
// }
// robot1.ok()
// robot3.a = 11
// robot3.inside.push(9)
// //好恐怖啊
// //每个instance都可以改写prototype
// // 那叫 monkey patch
// // 写代码的时候不允许乱改的
// //比如母是animal
// //子是不同的动物
// //他们的this.food = ['banana', 'xxx','xxx]不一样
// //就要修改啊
// //这个场景不是很常见吗
// // this.food 不应该放在 prototype 上
// // prototype 上的一般都是一些 function
// // 所有 prototype 上的常量理论上都是不应该修改的
// robot3.b = 35346
// robot3.outside.push('kkk')
// //这个test是function
// // 这样写没有覆盖 prototype
// // 噢 对哦
// //只有array object会覆盖?
// // robot3.outside.push(1); 这样会修改
// // robot3.outside = []; 这样不会修改 prototype
// // 因为 object 和 array 是引用值
// robot3.test = function(){
// console.log('just kidding...')
// }
// console.log(robot1)
// console.log(robot1.outside)
// console.log(robot1.b)
// robot1.test()
// console.log('----------')
// console.log(robot2)
// console.log(robot2.outside)
// console.log(robot2.b)
// robot2.test()
// console.log('----------')
// console.log(robot3)
// console.log(robot3.outside)
// console.log(robot3.inside)
// console.log(robot3.b)
// console.log(robot3.a)
// robot3.test()
// console.log('----------')
// console.log(robot3 instanceof Robot)
// //what are you doing???
// // test
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment