//Object.create()创建对象
var obj = Object.create({aa:1,bb:2,cc:'c'});
obj.dd = 4;
console.log(obj.cc); // c
console.log(obj.hasOwnProperty("cc")); //false
console.log(obj.hasOwnProperty("dd")); // true
//仿Object.create()方法创建CreateObject函数
var obj = {aa:1,bb:2,cc:'c'};
function CreateObject(proto){
function F(){};
F.prototype = proto;
return (new F);
}
var newObj = CreateObj(obj);
//构造函数和原型结合创建对象举例
function Circle(r){
this.r = r;
}
Circle.prototype.circum = function(){
return (2*this.r*Math.PI).toFixed(2);
}
Circle.prototype.area = function(){
return (Math.pow(this.r,2)*Math.PI).toFixed(2);
}
var c = new Circle(3);
console.log(c.circum());
console.log(c.area());
//复制一个对象
function copyObj(obj){
var newObj = {};
for(key in obj){
newObj[key] = obj[key];
}
return newObj;
}
//类继承举例
//创建父类
function Father(){
this.familyName = 'Zhu';
this.money = 20;
}
//父类原型
Father.prototype.have= function(){
return 'I have $'+this.money+'.'
}
//创建子类
function Child(){
Father.apply(this,arguments);
this.toy = 'car';
}
//子类原型等于父类构造的新对象
Child.prototype = new Father();
//子类的构造函数重定向
Child.constructor = Child;
//子类可创建自己的方法
Child.prototype.play = function(){
return 'I play with a '+this.toy+'.'
}
//基于子类创建新对象
var child = new Child();
//extend方法 对象扩展
function extend(target,source){
for(k in source){
target[k] = source[k];
}
return target;
}
【前端学习笔记03】JavaScript对象相关方法及封装
程序员文章站
2022-05-10 23:00:09
...