标签:
var person={ name:"dog", age:20, };
var person={ name:"dog", age:20, getNmae:function(){ return this.name; } };
var person={}; person.name="age"; person.age=20; person.getName=function(){ return this.name; }
var obj=new Object(); obj.name="dog"; obj.getName=function(){ return this.name; }
function Person(name,age){ this.name=name; this.age=age; } var person=new Person("dog",20);
function Foo(){ }; console.log(Foo.prototype); //Object{} console.log(Foo.prototype .constructor); // function Foo(){}
function Foo(){}; console.log(Foo.prototype); //Object{} var f=new Foo(); console.log(f.__proto__); // Object{} console.log(Foo.prototype==f.__proto__) ; // true
function animal(name){ this.name=name; } animal.prototype.color="white"; var cat1=new animal("cat"); var cat2=new animal(‘dog‘); cat1.color; //white cat2.color; //white cat1.color==cat2.color; // true
function Foo(){}; Foo.prototype.name="cat"; var f1=new Foo(); var f2=new Foo(); f1.name="dog"; console.log(f1.name); //dog 来自实例 console.log(f2.name); // cat 来自原型
//不重写原型对象 function Foo(){}; var f1=new Foo(); Foo.prototype.name="cat"; Foo.prototype.getName=function(){ return this.name; //this指向调用该构造函数的实例对象 } f1.getName(); //cat //使用字面量重写原型对象 function Foo(){}; var f1=new Foo(); Foo.prototype={ name:"cat", getName:function(){ return this.name } } f1.getNmae(); // Uncaught TypeError:f1.getName is not a function(...) //因为重写原型对象断开了原型与已有对象的联系 解决方法:在重写之后再创建对象就可以了 var f2=new Foo(); f2.getName(); //cat;
function Foo(){}; Foo.prototype={ name:"cat", friends:[‘dog‘,‘xhdsh‘]; getName:function(){ return this.name } } var f1=new Foo(); var f2=new Foo(); f1.name="hh"; f1.friends=[‘hhhh‘,‘ssss‘]; console.log(f2.name); // cat //name是值类型,修改f1的name属性并不会影响其他实例对象该属性的值 console.log(f2.friends); // [‘hhh‘] //friends为引用类型,故修改f1.friends后f2.friends也会随之改变
function Foo(){}; console.log(Foo.__proto__); //function(){} console.log(Function.prototype); //function(){} console.log(Foo.__proto__==Function.prototype); //true
console.log(Function instanceof Function); //true onsole.log(Function.prototype.__proto__); // Object{}
function Foo(){}; var f=new Foo(); Foo.prototype.age=12; f.name="dog"; console.log(f.age); console.log(f.hasOwnProperty(‘name‘)); //true console.log(f.hasOwnProperty(‘age‘)); //false
function Foo(){}; Foo.prototype.age=12; var f=new Foo(); f.name="dog"; console.log(Object.getPrototypeOf(f)); // Object{age:12}
var a={age:12}; var b=Object.setPrototypeOf({},a); console.log(b.age); //12
标签:
原文地址:http://www.cnblogs.com/chtt/p/5800316.html