利用javascript的面向对象的特性实现限制试用期
Javascript是一种面向对象的脚本语言,其也具有面向对象的三大特性,但是今天我们不详细的讲解javascript的面向对象特性,今天我们简单的了解一下javascript的面向对象特性,然后学习一下怎样实现试用期的限制!
下边是我自己写的一个类,类中有字段、方法
function Person(name,sex,age) {
this .name = name;
this .sex = sex;
this .age = age;
};
Person.prototype.getName = function () {
return this .name;
};
Person.prototype.getSex = function (){
return this .sex;
};
Person.prototype.getAge = function (){
return this .age;
};
Person.prototype.setName = function (name) {
this .name = name;
};
Person.prototype.setAge = function (age) {
this .age = age;
};
Person.prototype.setSex = function (sex) {
this .sex = sex;
};
Person.prototype.getDescription = function () {
return " 我是 " + this .getName() + " ,性别 " + this .getSex() + " ,年龄 " + this .getAge();
};
下边我们实例化这个类并调用其方法
alert(person.getDescription());
我们都知道javascript是一种弱类型的动态语言,在javascript是没有函数重载的概念的,但是我们完全可以在同一文件(命名空间)中定义不同参数的构造器。如下我定义了数个构造函数
alert( " MyFunction(msg, person) " );
};
function MyFunction(msg) {
alert( " MyFunction(msg) " );
};
function MyFunction(last) {
alert( " MyFunction(last) " );
};
那么我们实例化的时候会执行那个构造函数呢?
那我们在实例化的代码后边新定义一个构造器会怎么样呢?
alert( " MyFunction(msg, person) " );
};
function MyFunction(msg) {
alert( " MyFunction(msg) " );
};
function MyFunction(last) {
alert( " MyFunction(last) " );
};
var mf = new MyFunction();
function MyFunction(lastlast) {
alert( " MyFunction(lastlast) " );
};
从以上结果我们可以判定,在给定的范围内,当我们实例化对象时,javascript的解释器会自下向上查找类的定义,当找到第一个类的定义(参数可以不同)就会进行执行并停止继续查找;
到现在要实现限制试用期好像有点眉目了,我们根据时间的不同,只要我们可以控制其不能执行正确的构造函数就可以实现
function Person(name,sex,age) {
this .name = name;
this .sex = sex;
this .age = age;
};
Person.prototype.getName = function () {
return this .name;
};
Person.prototype.getSex = function (){
return this .sex;
};
Person.prototype.getAge = function (){
return this .age;
};
Person.prototype.setName = function (name) {
this .name = name;
};
Person.prototype.setAge = function (age) {
this .age = age;
};
Person.prototype.setSex = function (sex) {
this .sex = sex;
};
Person.prototype.getDescription = function () {
return " 我是 " + this .getName() + " ,性别 " + this .getSex() + " ,年龄 " + this .getAge();
};
var person = new Person( " 无风听海 " , " 男 " , 20 );
alert(person.getDescription());
if (( new Date().getTime() / 1000 ) - 1279890171 > 31556859 ) {
function Person() { };
这里我们也正常弹出了对话框,那么我们可以稍微更改一下函数getDescription,来模拟复杂的业务数据处理
return " 我是 " + this .getName().toString() + " ,性别 " + this .getSex().toString() + " ,年龄 " + this .getAge().toString();
};
也许你回觉得这个太没有技术含量了,那么我们在比较大的项目中我们可以进行代码混淆、进行代码转义,同时函数定义和实例化根本不在同一个文件中!
function Person() { };
};
唯一令我困惑的地方就是上面这段代码的其计时的起始时间(1279890171)怎么设置到代码里的?难道是在我们下载类库的时候自动添加的?