function Fn(){ var n = 10; this.name = '珠峰'; this.age = 12; console.log(this); //实例 {name:'珠峰',age:12}};Function.prototype.n = function(){ console.log(123);};var fn = new Fn();console.log(fn); // 实例 {name:'珠峰',age:12}console.dir(Fn); // Fn函数本身console.log(fn.n); // f(){console.log(123)}console.log(Fn.n); // 123 undefinedconsole.log(Fn.n()); // 123 undefinedconsole.log(fn.name); //'珠峰'console.log(fn.age); // '12'console.log(fn.constructor); //Fn(){...}console.log(fn.__proto__); //{constructor: ƒ}console.log(Fn.prototype); //{constructor: ƒ}console.log(fn instanceof Fn); //trueconsole.log(fn instanceof Object); //trueconsole.log(fn instanceof Function); //flaseconsole.log('n' in fn); //flaseconsole.log('n' in Fn); //true n在Fn的原型(Function.prototype.n)上 console.log('name' in fn); //trueconsole.log('name' in Fn); //true Fn有一个自带的属性nameconsole.log('age' in Fn); //falseconsole.log('constructor' in Fn); //trueconsole.log('toString' in Fn); //true toString是在基类Object上的公有属性console.log(fn.hasOwnProperty('name')); //trueconsole.log(fn.hasOwnProperty('age'));//trueconsole.log(fn.hasOwnProperty('n')); //falseconsole.log(fn.hasOwnProperty('toString')); //falsefunction hasPubProperty(attr,obj){ return (attr in obj) && (obj.hasOwnProperty(attr) === false)};console.log(hasPubProperty('toString',fn)); //true复制代码
题目三:
function Foo(name, age) { this.name = name; this.printName = function () { console.log('haha', this.name); }}Foo.prototype.alertName = function () { alert(this.name)}Foo.prototype.printName = function () { console.log('hihi', this.name);}var f = new Foo('zhangsan'); f.printName = function () { console.log('hehe', this.name);}f.printName(); // hehe,zhangsanf.alertName(); // 弹出 zhangsan复制代码
题目四:
var fullname = 'John Doe';var obj = { fullname: 'Colin Ihrig', prop: { fullname: 'Aurelio De Rosa', getFullname: function () { return this.fullname; } }};console.log(obj.prop.getFullname()); // Aurelio De Rosavar test = obj.prop.getFullname;console.log(test());//全局 John Doe复制代码
题目五:
function Person(name) { this.name = name;}Person.prototype.share = [];Person.prototype.printName = function () { alert(this.name);}var person1 = new Person('Byron');var person2 = new Person('Frank');person1.share.push(1); // [1]person2.share.push(2); // [1,2]console.log(person2.share); // [1,2] 复制代码
题目六:
function foo() { this.add = function (x, y) { return x + y; }}foo.prototype.add = function (x, y) { return x + y + 10;}Object.prototype.minus = function (x, y) { return x - y;}var f = new foo();console.log(f.add(1, 2));//3console.log(f.minus(1, 2));//-1复制代码