JS Object Introducation

本文探讨了JavaScript中的构造函数及原型链实现的面向对象编程(OOP),通过实例讲解了Person构造函数的创建与使用,深入理解JS的OOP语法。

Object对象中:变量方法+函数方法

// const brad = {
//   name:'Brad',
//   age:30
// }

// console.log(brad);
// console.log(brad.age);

//JS的OOP语法

//Person constructor
function Person(name,dob){
  this.name=name;
  //this.age=age;
  //function内的this为对象
  this.birthday = new Date(dob); 
        //string 传入date,生成date object
  this.calculateAge = function(){
    const diff = Date.now() - this.birthday.getTime(); //得到相差 date object
    const ageDate = new Date(diff);  //差的date object
    return Math.abs(ageDate.getUTCFullYear() - 1970);
  }                 //得到给定日期的年
}

//全局的this为window对象;

// const brad = new Person('Brad',36);
// const john = new Person('John',30);



// console.log(john.age);
// console.log(brad.age);

const brad = new Person('brad','9-10-1981');
console.log(brad.calculateAge());

一些无用的构造方法;

//Strings

const name1='Jeff';
const name2=new String('Jeff');  //得到一个object type


name2.foo = 'bar'; //加入property
console.log(name2);

console.log(typeof name2);

if(name2 == name1){       //name2不为string type ===也检查type 
  console.log('yes');     //name2 == name1 为true
}else {
  console.log('no');
}

//Number
const num1=5;
const num2 = new Number(5);

if(num1 == num2){       //name2不为string type ===也检查type 
  console.log('yes');     //name2 == name1 为true
}else {
  console.log('no');
}


//Boolean
const bool1= true;
const bool2 = new Boolean(true);

//Function
const getSum1=function(x,y){
  return x+y;
}

const getSum2 = new Function('x','y','return x+y'); //

console.log(getSum1(2,1));
console.log(getSum2(1,2));


//Object
const john1 = {name:'john'};  //为object

const john2= new Object({name:'John'}); //为object
console.log(john1);

//Arrays
const arr1=[1,2,3,4];  //object
const arr2 = new Array(1,2,3,4);  //object

console.log(arr1);


//Regular Expressions  //正则表达式
const re1=/\w+/;  //找一个多次出现的word
const re2=new RegExp('\\w+');

console.log(re);


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值